package com.marvels.financial.pay.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.marvels.financial.pay.bfpay.dto.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dragon.app.commons.constant.ErrorCode;
import com.dragon.app.ykd.dto.BankCardLoanDTO;
import com.dragon.loan.entity.AcLoanApplyInfo;
import com.dragon.loan.service.AcLoanApplyInfoServiceImpl;
import com.dragon.loan.service.LoanInfoIDragonService;
import com.fintech.common.enums.RespStatus;
import com.fintech.common.enums.ResultCode;
import com.fintech.third.constant.ResponseResult;
import com.fintech.third.constant.SmsTypeEnum;
import com.fintech.third.model.sms.SmsParameter;
import com.fintech.third.service.sms.SmsService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.marvels.approve.loan.api.LoanApplyProvideApi;
import com.marvels.approve.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.approve.loan.service.IMcamLoanApplyInfoService;
import com.marvels.common.constants.MarvelsConstant;
import com.marvels.common.constants.PageConstant;
import com.marvels.common.constants.PayContants;
import com.marvels.common.dto.UserDTO;
import com.marvels.common.dto.pay.MarvelsPayResultDTO;
import com.marvels.common.dto.pay.McfePaymentUserBindCard;
import com.marvels.common.dto.pay.McfeRepaymentTradeDetails;
import com.marvels.common.dto.pay.McfeSetDefaultCardLog;
import com.marvels.common.enums.BindStatusEnum;
import com.marvels.common.enums.PayStatusEnum;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.CacheUtils;
import com.marvels.common.utils.DateUtils;
import com.marvels.common.utils.GenerateReqNoUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.loan.api.FinancialILoanAfterInfoApi;
import com.marvels.financial.loan.dao.McfeCardBinInfoDao;
import com.marvels.financial.loan.dao.McfeCustomerLoanContractDao;
import com.marvels.financial.loan.dao.McfeLendingProcessDao;
import com.marvels.financial.loan.dto.ExtensionFunctionConditionDTO;
import com.marvels.financial.loan.dto.McfeCardBinInfoDTO;
import com.marvels.financial.loan.dto.McfeCustomerLoanContractDTO;
import com.marvels.financial.loan.dto.McfeLendingProcess;
import com.marvels.financial.loan.dto.RepaymentNoMobileDTO;
import com.marvels.financial.loan.service.ExtensionFunctionApi;
import com.marvels.financial.loan.service.LoanAuditApi;
import com.marvels.financial.pay.bfpay.service.BfPayApi;
import com.marvels.financial.pay.cjpay.dto.BindCardDTO;
import com.marvels.financial.pay.cjpay.service.CJPayApi;
import com.marvels.financial.pay.dao.McfeMerchantRechargeRecordMapper;
import com.marvels.financial.pay.dao.McfePaymentUserBindCardMapper;
import com.marvels.financial.pay.dao.McfeRepaymentTradeDetailsMapper;
import com.marvels.financial.pay.dto.McfeMerchantRechargeRecordDTO;
import com.marvels.financial.pay.dto.McfePaymentUserBindCardCondition;
import com.marvels.financial.pay.dto.MerchantRechargeDTO;
import com.marvels.financial.pay.dto.PayResultDto;
import com.marvels.financial.pay.dto.WithholdConditionDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.AgreementPaymentSignDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentQueryDTO;
import com.marvels.financial.pay.hjpay.dto.DirectPaymentSmsDTO;
import com.marvels.financial.pay.hjpay.dto.MerchantRechargePayDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentDTO;
import com.marvels.financial.pay.hjpay.dto.SinglePaymentQueryDTO;
import com.marvels.financial.pay.hjpay.service.HjPayApi;
import com.marvels.financial.pay.service.PayService;
import com.marvels.financial.pay.ybpay.YbPayService;
import com.marvels.financial.pay.yzfpay.YzfPayService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

/**
 *
* @ClassName: PayService
* @Description:对外支付接口类 --实现类
* @author 李瑶
* @date 2018年10月6日 下午4:13:04
*
 */
@Service
public class PayServiceImp implements PayService {

	private static MarvelsLogUtil logger = MarvelsLogUtil.getInstance();

	@Autowired
	private McfePaymentUserBindCardMapper mcamPaymentUserBindCardMapper;

	@Autowired
	private McfeRepaymentTradeDetailsMapper mcamRepaymentTradeDetailsMapper;

	@Autowired
	private HjPayApi hjPayApi;

//	@Autowired
//	private KqPayApi kqPayApi;

	@Autowired
	private CJPayApi cjPayApi;

	@Autowired
	private BfPayApi bfPayApi;
	@Autowired
	private YzfPayService yzfPayService;

	@Autowired
	private McfeCardBinInfoDao mcfeCardBinInfoDao;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessDao;

	@Autowired
	private McfeCustomerLoanContractDao mcfeCustomerLoanContractDao;

	@Autowired
	private IMcamLoanApplyInfoService mcamLoanApplyInfoService;

	@Autowired
	private McfeMerchantRechargeRecordMapper mcfeMerchantRechargeRecordMapper;

	@Value("${config.properties.path}")
	private  String configPropertiesPath;

	@Autowired
	private ExtensionFunctionApi extensionFunctionApi;

	@Autowired
	private FinancialILoanAfterInfoApi iLoanAfterInfoApi;

	@Autowired
	private LoanInfoIDragonService loanInfoIDragonService;

	@Autowired
	private LoanApplyProvideApi loanApplyProvideApi;

	@Autowired
	private AcLoanApplyInfoServiceImpl acLoanApplyInfoService;

	@Autowired
	private SmsService smsService;

	@Autowired
	private McfeLendingProcessDao mcfeLendingProcessMapper;

	@Autowired
	private LoanAuditApi loanAuditApi;

	@Override
	public MarvelsPayResultDTO queryBankList(String idno, String currentChannel) {
		List<McfePaymentUserBindCard> mcamPaymentUserBindCards = mcamPaymentUserBindCardMapper.selectBankListByIdno(idno, currentChannel, "0");
		logger.info("queryBankList============result："+JSON.toJSONString(mcamPaymentUserBindCards));
		return MarvelsPayResultDTO.getSuccessResult(mcamPaymentUserBindCards);
	}

	public MarvelsPayResultDTO updateDefaultCard(String idno, String currentChannel, String loanId, String bankCardNo) throws MarvelsBusinessException{
		McfePaymentUserBindCard userBindCardDto = new McfePaymentUserBindCard();
		userBindCardDto.setIdno(idno);
		userBindCardDto.setBankCardNo(bankCardNo);
		McfePaymentUserBindCard mcfePaymentUserBindCard = mcamPaymentUserBindCardMapper.selectBindCard(userBindCardDto);
		if(null == mcfePaymentUserBindCard) {
			throw new MarvelsBusinessException("该卡无效，无法设为默认卡");
		}

		return updateDefaultCard(idno,currentChannel,loanId,mcfePaymentUserBindCard.getId().intValue());
	}

	public MarvelsPayResultDTO updateDefaultCard(String idno, String currentChannel, String loanId,BankCardLoanDTO bankCardLoanDTO) throws MarvelsBusinessException{
		McfePaymentUserBindCard userBindCardDto = new McfePaymentUserBindCard();
		userBindCardDto.setIdno(idno);
		userBindCardDto.setBankCardNo(bankCardLoanDTO.getRepayAcct());
		McfePaymentUserBindCard mcfePaymentUserBindCard = mcamPaymentUserBindCardMapper.selectBindCard(userBindCardDto);
		if(null == mcfePaymentUserBindCard
				||!"BIND_SUCCESS".equals(mcfePaymentUserBindCard.getStatus())
				|| !"0".equals(mcfePaymentUserBindCard.getUnbindStatus())
				|| !currentChannel.equals(mcfePaymentUserBindCard.getChannel())) {
			throw new MarvelsBusinessException("该卡无效，无法设为默认卡");
		}

		logger.info("用户idno="+idno+",bankCardLoanDTO="+JSON.toJSONString(bankCardLoanDTO)+"开始设置默认银行卡");
		String key = "setDefaultCard_" + idno;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, idno);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				String bankCardNo = mcfePaymentUserBindCard.getBankCardNo();
				String bankName = mcfePaymentUserBindCard.getBankName();
				String custName = mcfePaymentUserBindCard.getCustName();
				McamLoanApplyInfoDTO mcamLoanApplyInfo = mcamLoanApplyInfoService.findMcamLoanApplyInfo(loanId);
				McfeLendingProcess mcfeLendingProcess = null;
				if(null != mcamLoanApplyInfo) {
					mcfeLendingProcess = mcfeLendingProcessDao.selectByCustIdNumber(mcamLoanApplyInfo.getCustCardNo());
					if(null != mcfeLendingProcess) {
						// 有放款中的单，不允许设置
						if(StrUtil.equalsAny(mcfeLendingProcess.getStatus(), "F10", "F7")){
							throw new MarvelsBusinessException("当前暂时不允许设置，请稍后再试");
						}

						// 如果放款表目前繁忙，则不允许设置
						if(!"0".equals(mcfeLendingProcess.getIsBusy())){
							throw new MarvelsBusinessException("当前暂时不允许设置，请稍后再试");
						}
					}
				}

				// 只是记录，方便前期有问题排查
				StringBuffer actionTableName = new StringBuffer();
				// 如果有在途单，则看情况修改表中记录
				if(StrUtil.isNotEmpty(loanId)){
					// 先修改进件表中的银行卡信息
					AcLoanApplyInfo loan = new AcLoanApplyInfo();
					loan.setReceiveAcct(bankCardLoanDTO.getReceiveAcct());
					loan.setReceiveAcctName(bankCardLoanDTO.getReceiveAcctName());
					loan.setReceiveBankName(bankCardLoanDTO.getReceiveBankName());
					loan.setRepayAcct(bankCardNo);
					loan.setRepayAcctName(custName);
					loan.setRepayBankName(bankName);
					loan.setLoanId(loanId);
					acLoanApplyInfoService.updateByLoanId(loan);
					actionTableName.append("ac_loan_apply_info、");
					// 如果不为空，说明已经走到了核心后台，再选择性修改表数据
					if(mcamLoanApplyInfo != null){
						// 修改核心后台的银行卡信息（如果没到新核心后台，修改记录会为0）
						com.marvels.approve.loan.dto.McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = new com.marvels.approve.loan.dto.McamLoanApplyInfoDTO();
						mcamLoanApplyInfoDTO.setLoanId(loanId);
						mcamLoanApplyInfoDTO.setReceiveAcctNo(bankCardLoanDTO.getReceiveAcct());
						mcamLoanApplyInfoDTO.setReceiveAcctName(bankCardLoanDTO.getReceiveAcctName());
						mcamLoanApplyInfoDTO.setReceiveBankName(bankCardLoanDTO.getReceiveBankName());
						mcamLoanApplyInfoDTO.setPaymentBankName(bankName);
						mcamLoanApplyInfoDTO.setPaymentAcctName(custName);
						mcamLoanApplyInfoDTO.setPaymentAcctNo(bankCardNo);
						int count = loanApplyProvideApi.modifyLoanApplyInfo(mcamLoanApplyInfoDTO);
						if(count > 0) actionTableName.append("mcfe_loan_apply_info、");

						if("F03".equals(mcamLoanApplyInfo.getStatus()) && null != mcfeLendingProcess){
							//修改放款表中的银行卡
							McfeLendingProcess mcfeLending = new McfeLendingProcess();
							mcfeLending.setId(mcfeLendingProcess.getId());
							mcfeLending.setPaymentBankName(bankName);
							mcfeLending.setPaymentAcctName(custName);
							mcfeLending.setPaymentAcctNo(bankCardNo);
							mcfeLending.setReceiveBankName(bankName);
							mcfeLending.setReceiveAcctName(custName);
							mcfeLending.setReceiveAcctNo(bankCardNo);
							count = mcfeLendingProcessDao.updateByPrimaryKeySelective(mcfeLending);
							if(count > 0) actionTableName.append("mcfe_lending_process、");
						}
						//修改合同表中的银行卡
						McfeCustomerLoanContractDTO customerLoanContract = new McfeCustomerLoanContractDTO();
						customerLoanContract.setLoanId(loanId);
						customerLoanContract.setPaymentBankName(bankName);
						customerLoanContract.setPaymentAcctName(custName);
						customerLoanContract.setPaymentAcctNo(bankCardNo);
						count = mcfeCustomerLoanContractDao.updateBankCardByLoanId(customerLoanContract);
						if(count > 0) actionTableName.append("mcfe_customer_loan_contract");
					}
				}

				// 记录日志
				McfeSetDefaultCardLog setDefaultCardLog = new McfeSetDefaultCardLog();
				setDefaultCardLog.setIdNo(idno);
				setDefaultCardLog.setActionLoanId(loanId);
				setDefaultCardLog.setActionTableName(actionTableName.toString());
				setDefaultCardLog.setCurrentDefaultCard(bankCardNo);
				setDefaultCardLog.setCurrentId(mcfePaymentUserBindCard.getId().toString());
				mcamPaymentUserBindCardMapper.insertSetDefaultCardLog(setDefaultCardLog);

				// 设置为默认卡
				McfePaymentUserBindCard modifyBindCard = new McfePaymentUserBindCard();
				mcfePaymentUserBindCard.setIdno(idno);
				mcfePaymentUserBindCard.setId(mcfePaymentUserBindCard.getId().longValue());
				mcamPaymentUserBindCardMapper.updateDefaultCard(modifyBindCard);
				logger.info("用户idno="+idno+",bankCardLoanDTO="+JSON.toJSONString(bankCardLoanDTO)+"设置默认银行卡成功");
			}else{
				logger.info("用户idno="+idno+",bankCardLoanDTO="+JSON.toJSONString(bankCardLoanDTO)+"设置默认银行卡过于频繁");
				return MarvelsPayResultDTO.getFailResult("-1","请不要重复进行操作");
			}
			return MarvelsPayResultDTO.getSuccessResult(null);
		} catch(MarvelsBusinessException e){
			logger.error("用户idno="+idno+",bankCardLoanDTO="+JSON.toJSONString(bankCardLoanDTO)+"设置默认银行卡失败",e);
			return MarvelsPayResultDTO.getFailResult("-1", e.getMessage());
		} catch (Exception e) {
			logger.error("用户idno="+idno+",bankCardLoanDTO="+JSON.toJSONString(bankCardLoanDTO)+"设置默认银行卡异常",e);
			return MarvelsPayResultDTO.getFailResult("-1", "设置银行卡异常");
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}
	}

	/**
	 * 设置默认卡（会作用到进件表 + 放款表 + 合同表）
	 */
	@Override
	public MarvelsPayResultDTO updateDefaultCard(String idno, String currentChannel, String loanId, Integer bankCardId) throws MarvelsBusinessException{
		logger.info("用户idno="+idno+",bankCardId="+bankCardId+"开始设置默认银行卡");
		String key = "setDefaultCard_" + idno;
		boolean isNotLock = false;
		try {
			isNotLock = CacheUtils.isNotLock(key, idno);
			if (isNotLock) {
				// 先将这个key设置过期时间
				CacheUtils.setExpire(key, 60);
				// 先查询设置的卡是否符合要求
				McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByPrimaryKey(bankCardId.longValue());
				logger.info("用户idno="+idno+",设置默认银行卡信息：" + JSONObject.toJSONString(mcamPaymentUserBindCard));
				if(mcamPaymentUserBindCard == null ||
						!"BIND_SUCCESS".equals(mcamPaymentUserBindCard.getStatus()) ||
						!"0".equals(mcamPaymentUserBindCard.getUnbindStatus()) ||
						!currentChannel.equals(mcamPaymentUserBindCard.getChannel())){
					throw new MarvelsBusinessException("该卡无效，无法设为默认卡");
				}
				String bankCardNo = mcamPaymentUserBindCard.getBankCardNo();
				String bankName = mcamPaymentUserBindCard.getBankName();
				String custName = mcamPaymentUserBindCard.getCustName();

				// 只是记录，方便前期有问题排查
				StringBuffer actionTableName = new StringBuffer();
				// 如果有在途单，则看情况修改表中记录
				if(StrUtil.isNotEmpty(loanId)){
					// 先修改进件表中的银行卡信息
					AcLoanApplyInfo loan = new AcLoanApplyInfo();
					loan.setReceiveAcct(bankCardNo);
					loan.setReceiveAcctName(custName);
					loan.setReceiveBankName(bankName);
					loan.setRepayAcct(bankCardNo);
					loan.setRepayAcctName(custName);
					loan.setRepayBankName(bankName);
					loan.setLoanId(loanId);
					loanInfoIDragonService.input(loan);
					actionTableName.append("ac_loan_apply_info、");
					// 如果不为空，说明已经走到了核心后台，再选择性修改表数据
					McamLoanApplyInfoDTO mcamLoanApplyInfo = mcamLoanApplyInfoService.findMcamLoanApplyInfo(loanId);
					if(mcamLoanApplyInfo != null){
						// 修改核心后台的银行卡信息（如果没到新核心后台，修改记录会为0）
						com.marvels.approve.loan.dto.McamLoanApplyInfoDTO mcamLoanApplyInfoDTO = new com.marvels.approve.loan.dto.McamLoanApplyInfoDTO();
						mcamLoanApplyInfoDTO.setLoanId(loanId);
						mcamLoanApplyInfoDTO.setReceiveBankName(bankName);
						mcamLoanApplyInfoDTO.setReceiveAcctName(custName);
						mcamLoanApplyInfoDTO.setReceiveAcctNo(bankCardNo);
						mcamLoanApplyInfoDTO.setPaymentBankName(bankName);
						mcamLoanApplyInfoDTO.setPaymentAcctName(custName);
						mcamLoanApplyInfoDTO.setPaymentAcctNo(bankCardNo);
						int count = loanApplyProvideApi.modifyLoanApplyInfo(mcamLoanApplyInfoDTO);
						if(count > 0) actionTableName.append("mcfe_loan_apply_info、");

						if("F03".equals(mcamLoanApplyInfo.getStatus())){
							McfeLendingProcess mcfeLendingProcess = mcfeLendingProcessDao.selectByCustIdNumber(mcamLoanApplyInfo.getCustCardNo());
							// 有放款中的单，不允许设置
							if(StrUtil.equalsAny(mcfeLendingProcess.getStatus(), "F10", "F7")){
								throw new MarvelsBusinessException("当前暂时不允许设置，请稍后再试");
							}

							// 如果放款表目前繁忙，则不允许设置
							if(!"0".equals(mcfeLendingProcess.getIsBusy())){
								throw new MarvelsBusinessException("当前暂时不允许设置，请稍后再试");
							}

							//修改放款表中的银行卡
							McfeLendingProcess mcfeLending = new McfeLendingProcess();
							mcfeLending.setId(mcfeLendingProcess.getId());
							mcfeLending.setPaymentBankName(bankName);
							mcfeLending.setPaymentAcctName(custName);
							mcfeLending.setPaymentAcctNo(bankCardNo);
							mcfeLending.setReceiveBankName(bankName);
							mcfeLending.setReceiveAcctName(custName);
							mcfeLending.setReceiveAcctNo(bankCardNo);
							count = mcfeLendingProcessDao.updateByPrimaryKeySelective(mcfeLending);
							if(count > 0) actionTableName.append("mcfe_lending_process、");
						}
						//修改合同表中的银行卡
						McfeCustomerLoanContractDTO customerLoanContract = new McfeCustomerLoanContractDTO();
						customerLoanContract.setLoanId(loanId);
						customerLoanContract.setPaymentBankName(bankName);
						customerLoanContract.setPaymentAcctName(custName);
						customerLoanContract.setPaymentAcctNo(bankCardNo);
						count = mcfeCustomerLoanContractDao.updateBankCardByLoanId(customerLoanContract);
						if(count > 0) actionTableName.append("mcfe_customer_loan_contract");
					}
				}

				// 记录日志
				McfeSetDefaultCardLog setDefaultCardLog = new McfeSetDefaultCardLog();
				setDefaultCardLog.setIdNo(idno);
				setDefaultCardLog.setActionLoanId(loanId);
				setDefaultCardLog.setActionTableName(actionTableName.toString());
				setDefaultCardLog.setCurrentDefaultCard(bankCardNo);
				setDefaultCardLog.setCurrentId(bankCardId.toString());
				mcamPaymentUserBindCardMapper.insertSetDefaultCardLog(setDefaultCardLog);

				// 设置为默认卡
				McfePaymentUserBindCard mcfePaymentUserBindCard = new McfePaymentUserBindCard();
				mcfePaymentUserBindCard.setIdno(idno);
				mcfePaymentUserBindCard.setId(bankCardId.longValue());
				mcamPaymentUserBindCardMapper.updateDefaultCard(mcfePaymentUserBindCard);
				logger.info("用户idno="+idno+",bankCardId="+bankCardId+"设置默认银行卡成功");
			}else{
				logger.info("用户idno="+idno+",bankCardId="+bankCardId+"设置默认银行卡过于频繁");
			}
			return MarvelsPayResultDTO.getSuccessResult(null);
		} catch(MarvelsBusinessException e){
			logger.error("用户idno="+idno+",bankCardId="+bankCardId+"设置默认银行卡失败",e);
			return MarvelsPayResultDTO.getFailResult("-1", e.getMessage());
		} catch (Exception e) {
			logger.error("用户idno="+idno+",bankCardId="+bankCardId+"设置默认银行卡异常",e);
			return MarvelsPayResultDTO.getFailResult("-1", "设置默认银行卡异常");
		} finally {
			if (!CacheUtils.isNotLock(key, loanId)) {// 如果是锁住的将所释放
				CacheUtils.del(key);
			}
		}
	}
	/**
	 *
	* @Title: queryBindedList
	* @Description: 查询用户的绑卡列表--全部卡（成功和非成功的都有）
	* @param idno 身份证
	* @param channel 渠道 yb 易宝  后续渠道可进行拓展
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:16:28
	 */
	@Override
	public MarvelsPayResultDTO queryBindedList(String idno,String channel){
		//查看用户在易宝的尚未解绑的绑卡列表
		List<McfePaymentUserBindCard> mcamPaymentUserBindCards = mcamPaymentUserBindCardMapper.selectListByIdno(idno, channel, "0");
		logger.info("queryBindedList============result："+JSON.toJSONString(mcamPaymentUserBindCards));
		return MarvelsPayResultDTO.getSuccessResult(mcamPaymentUserBindCards);

	}


	/**
	 *
	* @Title: queryBindedSuccessList
	* @Description: 客户绑定成功，尚未解绑的绑卡列表
	* @param idno
	* @param channel
	* @return
	* @author 李瑶
	* @date 2018年11月2日 下午5:12:07
	 */
	public MarvelsPayResultDTO queryBindedSuccessList(String idno,String channel){
		//查看用户在易宝的尚未解绑的绑卡列表--绑定成功
		List<McfePaymentUserBindCard> mcamPaymentUserBindCards = mcamPaymentUserBindCardMapper.selectBindSuccessListByIdno(idno, channel);
		logger.info("queryBindedList============result："+JSON.toJSONString(mcamPaymentUserBindCards));
		return MarvelsPayResultDTO.getSuccessResult(mcamPaymentUserBindCards);
	}

	/**
	 *
	* @Title: queryBind
	* @Description: 查看客户某张银行卡的绑卡情况
	* @param idno
	* @param bindCardNo
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:18:58
	 */
	@Override
	public MarvelsPayResultDTO queryBind(String idno,String bindCardNo,String channel){
		McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
		McfePaymentUserBindCardCondition.setIdno(idno);
		McfePaymentUserBindCardCondition.setBankCardNo(bindCardNo);
		McfePaymentUserBindCardCondition.setChannel(channel);
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);

		return MarvelsPayResultDTO.getSuccessResult(mcamPaymentUserBindCard);
	}

	/**
	 *
	* @Title: preBind
	* @Description:预绑卡
	* @param param 预绑卡入参
	* @param  channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:19:52
	 */
	@Override
	public MarvelsPayResultDTO preBind(Map<String, Object> param,String channel){
		String requestNo = YbPayService.getReuqestNum(channel);
		Date date = new Date();
		logger.info("preBind============入参："+param.toString());
		String bankCardNo = (String)param.get("bankCardNo");
		String idno = (String)param.get("idno");
		String userName = (String)param.get("userName");
		String bankCode = (String)param.get("bankCode");
		String bankName = (String)param.get("bankName");
		String phone = (String)param.get("phone");
		if(StringUtils.isEmpty(bankCardNo) || StringUtils.isEmpty(idno) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(phone)){
			return MarvelsPayResultDTO.getFailResult("-1", "必要参数不能为空");
		}
		/*if(StringUtils.isEmpty(bankName)){//前端传的银行名称为空则查卡bin
			McfeCardBinInfoDTO infoDTO= mcfeCardBinInfoDao.selectByBankCard(bankCardNo);
			bankName=infoDTO.getBankName();
		}*/
		// 查数据库获取银行卡名称，前端控制有问题
		McfeCardBinInfoDTO infoDTO = mcfeCardBinInfoDao.selectByBankCard(bankCardNo);
		if(infoDTO != null && StrUtil.isNotEmpty(infoDTO.getBankName())){
			bankName = infoDTO.getBankName();
		}
		try {
			McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
			McfePaymentUserBindCardCondition.setIdno(idno);
			McfePaymentUserBindCardCondition.setBankCardNo(bankCardNo);
			McfePaymentUserBindCardCondition.setChannel(channel);
			McfePaymentUserBindCardCondition.setPhone(phone);
			McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
			if(mcamPaymentUserBindCard == null){
				//尚未绑卡
				logger.info("preBind==========用户idno="+idno+",尚未绑定银行卡bankCardNo="+bankCardNo);
				mcamPaymentUserBindCard = new McfePaymentUserBindCard();
				mcamPaymentUserBindCard.setRequestNo(requestNo);
				mcamPaymentUserBindCard.setBankCardNo(bankCardNo);
				mcamPaymentUserBindCard.setChannel(channel);
				mcamPaymentUserBindCard.setCreatedBy("sys");
				mcamPaymentUserBindCard.setCreatedDate(date);
				mcamPaymentUserBindCard.setCustName(userName);
				mcamPaymentUserBindCard.setIdno(idno);
				mcamPaymentUserBindCard.setPhone(phone);
				mcamPaymentUserBindCard.setBankCode(bankCode);
				mcamPaymentUserBindCard.setBankName(bankName);
				mcamPaymentUserBindCardMapper.insertSelective(mcamPaymentUserBindCard);
			}
			mcamPaymentUserBindCard.setRequestNo(requestNo);
			String status = mcamPaymentUserBindCard.getStatus();
//			if("BIND_SUCCESS".equals(status)){
//				//已经绑卡成功，则直接返回绑卡成功消息
//				logger.info("preBind==========用户idno="+idno+",尚未绑定银行卡bankCardNo="+bankCardNo+",已成功绑卡，无需重复发起");
//				return MarvelsPayResultDTO.getFailResult(PayContants.YB_BINDED_CARD_CODE.getCode(), PayContants.YB_BINDED_CARD_CODE.getMessage());
//			}
			logger.info("preBind==========用户idno="+idno+",bankCardNo="+bankCardNo+"开始进行预绑卡");
			String returnStatus = "BIND_SUCCESS";
//			if(StringUtils.isBlank(channel)||PayContants.PAY_CHANNEL_BF.getCode().equals(channel)) {
			if(StringUtils.isBlank(channel)) {
				//如果支付渠道未配置则平台发送短信验证码 宝付先走平台短信
				SmsParameter smsParam = new SmsParameter();
				smsService.sendSms(phone, smsParam, SmsTypeEnum.LOGIN);
//				if(!StringUtils.equalsIgnoreCase(responseResult.getErrorCode(), RespStatus.SUCCESS.getCode()+"")) {
//					return MarvelsPayResultDTO.getFailResult(channel, PayContants.PAY_NO_PRE_BIND.getMessage());
//				}
				returnStatus = "TO_VALIDATE";
			}else if(PayContants.PAY_CHANNEL_YZF.getCode().equals(channel)) {
				//使用翼支付预绑卡
				if(StringUtils.isNotBlank(mcamPaymentUserBindCard.getPreBindOrderId()) && StringUtils.equalsIgnoreCase("TO_VALIDATE", mcamPaymentUserBindCard.getStatus())) {
					//已经有支付平台的预绑卡请求号则重新调用发送验证码接口
					McfePaymentUserBindCardCondition resultDto = yzfPayService.preBindCardAgain(mcamPaymentUserBindCard.getPreBindOrderId());
					if(StringUtils.equalsIgnoreCase(resultDto.getRespCode(), ResultCode.success.getResultCode())) {
						returnStatus = "TO_VALIDATE";
						mcamPaymentUserBindCard.setPreBindOrderId(resultDto.getPreBindOrderId());
						mcamPaymentUserBindCard.setPreBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
					}else {
						returnStatus = "BIND_FAIL";
					}
				}else {
					McfePaymentUserBindCardCondition resultDto = yzfPayService.preBindCard(mcamPaymentUserBindCard.getRequestNo(), mcamPaymentUserBindCard.getBankCardNo(),
							mcamPaymentUserBindCard.getIdno(), mcamPaymentUserBindCard.getCustName(), mcamPaymentUserBindCard.getPhone());
					if(StringUtils.equalsIgnoreCase(resultDto.getRespCode(), ResultCode.success.getResultCode())
							&& StringUtils.equalsIgnoreCase(resultDto.getStatus(), BindStatusEnum.PROCESS.toString())) {
						returnStatus = "TO_VALIDATE";
						mcamPaymentUserBindCard.setPreBindOrderId(resultDto.getPreBindOrderId());
						mcamPaymentUserBindCard.setPreBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
					}else {
						returnStatus = "BIND_FAIL";
					}
				}
			}else if(PayContants.PAY_CHANNEL_BF.getCode().equals(channel)){
				BaoFuPrebindCardDTO bindCardDTO = new BaoFuPrebindCardDTO();
				bindCardDTO.setBankNumber(mcamPaymentUserBindCard.getBankCardNo());
				bindCardDTO.setMobile(mcamPaymentUserBindCard.getPhone());
				bindCardDTO.setIdNumber(mcamPaymentUserBindCard.getIdno());
				bindCardDTO.setRealName(mcamPaymentUserBindCard.getCustName());
				bindCardDTO.setOrderNumber(mcamPaymentUserBindCard.getRequestNo());
				Map<String, Object> resultMap = bfPayApi.baoFuPrebindCard(bindCardDTO);
//				McfePaymentUserBindCardCondition resultDto = new McfePaymentUserBindCardCondition();
//				resultDto.setRespCode(resultMap.get("errorcode").toString());
//				resultDto.setRespMsg(resultMap.get("errormsg").toString());
//				resultDto.setStatus(resultMap.get("status").toString());
//				resultDto.setBankCardNo(bindCardDTO.getBankNumber());
//				if(StringUtils.equalsIgnoreCase(resultDto.getRespCode(), ResultCode.success.getResultCode())
//						&& StringUtils.equalsIgnoreCase(resultDto.getStatus(), BindStatusEnum.PROCESS.toString())){
//					returnStatus = "TO_VALIDATE";
//					mcamPaymentUserBindCard.setUniqueCode(resultMap.get("uniqueCode").toString());
//					mcamPaymentUserBindCard.setPreBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
//				}else{
//					returnStatus = "BIND_FAIL";
//				}
				if(resultMap.get("status").toString().equals("TO_VALIDATE")){
					mcamPaymentUserBindCard.setUniqueCode(resultMap.get("uniqueCode").toString());
					mcamPaymentUserBindCard.setPreBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
				}
				returnStatus = resultMap.get("status").toString();
//				bfPayApi.baoFuPrebindCard()
//				if(StringUtils.isNotBlank(mcamPaymentUserBindCard.getPreBindOrderId()) && StringUtils.equalsIgnoreCase("TO_VALIDATE", mcamPaymentUserBindCard.getStatus())) {
//
//				}
			}
			mcamPaymentUserBindCard.setStatus(returnStatus);
			mcamPaymentUserBindCardMapper.updateByPrimaryKeySelective(mcamPaymentUserBindCard);
			Map<String, String> returnMap = new HashMap<>();
			returnMap.put("returnStatus", returnStatus);
			returnMap.put("requestNo", requestNo);
			return MarvelsPayResultDTO.getSuccessResult(returnMap);
		}catch (Exception e) {
			logger.error("preBind==========用户idno="+idno+",bankCardNo="+bankCardNo+"预绑卡异常",e);
			return MarvelsPayResultDTO.getFailResult("-1", "预绑卡异常");
		}

	}

	/**
	 *
	* @Title: bindCard
	* @Description:绑卡  （短信校验）
	* @param requestNo 请求单号
	* @param validateCode 验证码
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:22:50
	 */
	@Override
	public MarvelsPayResultDTO bindCard(String requestNo,String validateCode,String channel,String mobileNum){
		if(StringUtils.isEmpty(requestNo) || StringUtils.isEmpty(validateCode) ){
			return MarvelsPayResultDTO.getFailResult("-1", "绑卡确认验证码或预绑卡请求单号不能为空");
		}else if(StringUtils.isBlank(mobileNum)) {
			return MarvelsPayResultDTO.getFailResult("-1", "手机号缺失");
		}
		logger.info("Bind==========入参requestNo="+requestNo+"验证码validateCode="+validateCode+"channel:"+channel);
		try {
			McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
			McfePaymentUserBindCardCondition.setRequestNo(requestNo);
			McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
			if(mcamPaymentUserBindCard == null){
				return MarvelsPayResultDTO.getFailResult("-1", "没有查询到正确的预绑卡信息");
			}

			String status  = mcamPaymentUserBindCard.getStatus();
			if("BIND_SUCCESS".equals(status)){
				return MarvelsPayResultDTO.getSuccessResult(status);
			}else if(!"TO_VALIDATE".equals(status)){
				return MarvelsPayResultDTO.getFailResult(PayContants.PAY_NO_PRE_BIND.getCode(), PayContants.PAY_NO_PRE_BIND.getMessage());
			}

			String returnStatus = "BIND_FAIL";
			if(StringUtils.isBlank(channel)) {
				//如果没有接支付通道则验证自己平台发送的短信验证码
//				if (!smsService.checkCode(mobileNum, validateCode, SmsTypeEnum.LOGIN.getName())) {
//					return MarvelsPayResultDTO.getFailResult(ErrorCode.FAIL, "验证码错误");
//				}
				returnStatus = "BIND_SUCCESS";
			}

			if(PayContants.PAY_CHANNEL_YZF.getCode().equals(channel)) {
				McfePaymentUserBindCardCondition resultDto = yzfPayService.bindCard(mcamPaymentUserBindCard.getPreBindOrderId(), mcamPaymentUserBindCard.getIdno(), validateCode);
				if(StringUtils.equalsIgnoreCase(resultDto.getRespCode(), ResultCode.success.getResultCode())
						&& StringUtils.equalsIgnoreCase(resultDto.getStatus(), BindStatusEnum.SUCCESS.toString())) {
					returnStatus = "BIND_SUCCESS";
					mcamPaymentUserBindCard.setPreBindOrderId(resultDto.getPreBindOrderId());
					mcamPaymentUserBindCard.setBindOrderId(resultDto.getBindOrderId());
					mcamPaymentUserBindCard.setBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
				}else {
					returnStatus = "BIND_FAIL";
				}
			}
			if(PayContants.PAY_CHANNEL_BF.getCode().equals(channel)){
				BaoFuBindCardDTO bindCardDTO = new BaoFuBindCardDTO();
				bindCardDTO.setUniqueCode(mcamPaymentUserBindCard.getUniqueCode());
				bindCardDTO.setSmsCode(validateCode);
				bindCardDTO.setOrderNumber(YbPayService.getReuqestNum(channel));
				Map<String,Object> result = bfPayApi.baoFuBindCard(bindCardDTO);
				returnStatus = result.get("status").toString();
				if(returnStatus.equals("BIND_SUCCESS")){
					mcamPaymentUserBindCard.setBindOrderId(result.get("signedId").toString());
					mcamPaymentUserBindCard.setBindTime(DateUtil.formatLocalDateTime(LocalDateTime.now()));
				}
			}
			mcamPaymentUserBindCard.setStatus(returnStatus);
			mcamPaymentUserBindCardMapper.updateByPrimaryKeySelective(mcamPaymentUserBindCard);
			return MarvelsPayResultDTO.getSuccessResult(returnStatus);
		} catch(Exception e){
			logger.error("Bind==========用户requestNo="+requestNo+"绑卡异常",e);
			return MarvelsPayResultDTO.getFailResult("-1", "预绑卡异常");
		}
	}

	/**
	 *
	* @Title: resolveYbBindReturnData
	* @Description:解析绑卡返回数据
	* @param mcamPaymentUserBindCard
	* @param preData
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午7:21:00
	 */
	private String resolveYbBindReturnData(McfePaymentUserBindCard mcamPaymentUserBindCard,Map<String,Object> preData){
		String errorcode = (String)preData.get("errorcode");
		String msg = (String)preData.get("errormsg");
		String status = (String)preData.get("status");
		String yborderid = (String)preData.get("yborderid");
		mcamPaymentUserBindCard.setBindOrderId(yborderid);
		mcamPaymentUserBindCard.setCode(errorcode);
		mcamPaymentUserBindCard.setMsg(msg);
		mcamPaymentUserBindCard.setBindTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
		mcamPaymentUserBindCard.setStatus(status);
		mcamPaymentUserBindCard.setUpdatedBy("sys");
		mcamPaymentUserBindCard.setUpdatedDate(new Date());


		//先写死数据方便测试
		/*mcamPaymentUserBindCard.setBindOrderId("12312312312");
		mcamPaymentUserBindCard.setStatus("BIND_SUCCESS");
		return "BIND_SUCCESS";*/

		return status;
	}

	/**
	 *
	* @Title: unbind
	* @Description:解绑
	* @param idno 身份证
	* @param bindCardNo 银行卡号
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:23:46
	 */
	@Override
	public MarvelsPayResultDTO unbind(String idno,String bindCardNo,String channel){
		McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
		McfePaymentUserBindCardCondition.setIdno(idno);
		McfePaymentUserBindCardCondition.setBankCardNo(bindCardNo);
		McfePaymentUserBindCardCondition.setChannel(channel);
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
		if(mcamPaymentUserBindCard == null){
			return MarvelsPayResultDTO.getFailResult("-1", "未查询到客户的绑定信息");
		}
		if(PayContants.PAY_CHANNEL_YB.getCode().equals(channel)){
			Map<String, Object> unbindData = YbPayService.unbind(idno, bindCardNo);
			String errorcode = (String)unbindData.get("errorcode");
			String errormsg = (String)unbindData.get("errormsg");
			String status = (String)unbindData.get("status");
			if("SUCCESS".equals(status)){
				mcamPaymentUserBindCard.setUnbindStatus("1");
				mcamPaymentUserBindCard.setUpdatedDate(new Date());
				mcamPaymentUserBindCardMapper.updateByPrimaryKeySelective(mcamPaymentUserBindCard);
				return MarvelsPayResultDTO.getSuccessResult(null);
			}

		}else if(PayContants.PAY_CHANNEL_YZF.getCode().equals(channel)) {
			McfePaymentUserBindCardCondition resultDto = yzfPayService.unbind(mcamPaymentUserBindCard.getPreBindOrderId(), mcamPaymentUserBindCard.getIdno());
			if(StringUtils.equalsIgnoreCase(resultDto.getRespCode(), ResultCode.success.getResultCode())
					&& StringUtils.equalsIgnoreCase(resultDto.getStatus(), BindStatusEnum.SUCCESS.toString())) {
				mcamPaymentUserBindCard.setUnbindStatus("1");
				mcamPaymentUserBindCard.setUpdatedDate(new Date());
				mcamPaymentUserBindCardMapper.updateByPrimaryKeySelective(mcamPaymentUserBindCard);
				return MarvelsPayResultDTO.getSuccessResult(null);
			}else if(StringUtils.equalsIgnoreCase(resultDto.getStatus(), BindStatusEnum.UNBIND.toString())) {
				return MarvelsPayResultDTO.getFailResult("-1", "该卡未绑定");
			}
		}
		return MarvelsPayResultDTO.getFailResult("-1", "解绑失败");
	}

//	/**
//	 *
//	* @Title: withhold
//	* @Description:代扣
//	* @param idno 身份证
//	* @param requestNo 请求编号
//	* @param bindCard 银行卡号
//	* @param amount 金额  小数点后两位
//	* @param title 代扣标题
//	* @param channel 渠道 yb 易宝  后续渠道可进行拓
//	* @return
//	* @author 李瑶
//	* @date 2018年10月10日 下午3:24:07
//	 */
//	@Override
//	public MarvelsPayResultDTO withhold(String requestNo,String idno,String bindCard,String amount,String title,String channel ){
//		logger.info("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"开始");
//		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = null;
//		try {
//			logger.info("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"开始发送端口请求");
//			if(PayContants.PAY_CHANNEL_YB.getCode().equals(channel)){
//				mcamRepaymentTradeDetails = initWithhold(requestNo,idno, bindCard, amount, title, channel);
//				Map<String, Object> payResult = YbPayService.withhold("1", mcamRepaymentTradeDetails.getPayOrderNumber(), idno, bindCard, amount, title);
//				resolveYbWithholdReturnData(mcamRepaymentTradeDetails, payResult);
//			}
//			if(PayContants.PAY_CHANNEL_HJ.getCode().equals(channel)){//汇聚通道
//				//先查询汇聚的绑卡记录是否存在
//				McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
//				McfePaymentUserBindCardCondition.setIdno(idno);
//				McfePaymentUserBindCardCondition.setBankCardNo(bindCard);
//				McfePaymentUserBindCardCondition.setChannel(channel);
//				McfePaymentUserBindCardCondition.setStatus("BIND_SUCCESS");
//				McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
//				if(mcamPaymentUserBindCard!=null && StringUtils.isNotEmpty(mcamPaymentUserBindCard.getBindOrderId())){//记录不是空且签约号不是空
//					AgreementPaymentDTO agreementPaymentDTO=new AgreementPaymentDTO();
//					String orderNo=GenerateReqNoUtils.transctionReq2("HJXYDK",24);
//					mcamRepaymentTradeDetails = hjInitWithhold(requestNo,idno, bindCard, amount, title,orderNo);
//					agreementPaymentDTO.setQ1_OrderNo(orderNo);
//					agreementPaymentDTO.setQ2_Amount(new BigDecimal(amount));
//					agreementPaymentDTO.setQ4_ProductName("协议代扣");
//					agreementPaymentDTO.setS9_bankSignId(mcamPaymentUserBindCard.getBindOrderId());
//					agreementPaymentDTO.setS4_PayerBankCardNo(mcamPaymentUserBindCard.getBankCardNo());
//					Map<String, Object> map=hjPayApi.agreementPayment(agreementPaymentDTO);//走协议代扣
//					resolveHjWithholdReturnData(mcamRepaymentTradeDetails,map);
//				}else{
//					String orderNo=GenerateReqNoUtils.transctionReq2("HJDK",24);
//					mcamRepaymentTradeDetails = hjInitWithhold(requestNo,idno, bindCard, amount, title,orderNo);
//					DirectPaymentDTO dDirectPaymentDTO=new DirectPaymentDTO();
//					dDirectPaymentDTO.setQ1_OrderNo(orderNo);
//					McfeLendingProcess mcfeLendingProcess=mcfeLendingProcessDao.selectByCustIdNumber(idno);
//					dDirectPaymentDTO.setS1_PayerName(mcfeLendingProcess.getCustName());
//					dDirectPaymentDTO.setS3_PayerCardNo(idno);
//					dDirectPaymentDTO.setS4_PayerBankCardNo(bindCard);
//					dDirectPaymentDTO.setS7_BankMobile(mcfeLendingProcess.getCustMobile());
//					dDirectPaymentDTO.setQ2_Amount(new BigDecimal(amount));
//					dDirectPaymentDTO.setQ4_ProductName("直接代扣");
//					Map<String, Object> map=hjPayApi.directPayment(dDirectPaymentDTO);//走直接代扣
//					resolveHjWithholdReturnData(mcamRepaymentTradeDetails,map);
//				}
//			}
//			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
//		} catch (MarvelsBusinessException e1){
//			return MarvelsPayResultDTO.getFailResult("-1", e1.getMessage());
//		}catch (Exception e) {
//			logger.error("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"异常",e);
//			if(mcamRepaymentTradeDetails!=null){
//				mcamRepaymentTradeDetails.setResult("-3");
//				mcamRepaymentTradeDetails.setUpdatedDate(new Date());
//				mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
//			}
//			return MarvelsPayResultDTO.getFailResult("-2", "系统异常");
//		}
//
//
//	}


	/**
	 * 汇聚代扣初始化参数
	 * @param conditionDTO
	 * @return
	 * @throws MarvelsBusinessException
	 */
	private McfeRepaymentTradeDetails hjInitWithhold(WithholdConditionDTO conditionDTO )throws MarvelsBusinessException{
		String type=conditionDTO.getType();
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = new McfeRepaymentTradeDetails();
		if("1".equals(type)){
			mcamRepaymentTradeDetails.setCustName(conditionDTO.getCustName());
			mcamRepaymentTradeDetails.setBankName(conditionDTO.getBankName());
			mcamRepaymentTradeDetails.setMobileNo(conditionDTO.getMobile());
		}else{
			McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
			McfePaymentUserBindCardCondition.setIdno(conditionDTO.getIdno());
			McfePaymentUserBindCardCondition.setBankCardNo(conditionDTO.getBindCard());
			McfePaymentUserBindCardCondition.setChannel(PayContants.PAY_CHANNEL_HJ.getCode());
			McfePaymentUserBindCardCondition.setStatus("BIND_SUCCESS");
			McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
			if(mcamPaymentUserBindCard != null){
				mcamRepaymentTradeDetails.setBankCode(mcamPaymentUserBindCard.getBankCode());
				mcamRepaymentTradeDetails.setCustName(mcamPaymentUserBindCard.getCustName());
				mcamRepaymentTradeDetails.setBankName(mcamPaymentUserBindCard.getBankName());
			}
		}
		mcamRepaymentTradeDetails.setAmount(conditionDTO.getAmount());
		mcamRepaymentTradeDetails.setBankNumber(conditionDTO.getBindCard());
		mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_HJ.getCode());
		mcamRepaymentTradeDetails.setCreatedBy("sys");
		mcamRepaymentTradeDetails.setCreatedDate(new Date());
		mcamRepaymentTradeDetails.setIdNumber(conditionDTO.getIdno());
		mcamRepaymentTradeDetails.setRequestNo(conditionDTO.getRequestNo());
		mcamRepaymentTradeDetails.setPayOrderNumber(conditionDTO.getOrderNo());
		mcamRepaymentTradeDetails.setUpdatedBy("sys");
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetailsMapper.insertSelective(mcamRepaymentTradeDetails);
		logger.info("withhold============idno="+conditionDTO.getIdno()+",bindCard="+conditionDTO.getBindCard()
				+",amount="+conditionDTO.getAmount()+"channel="+PayContants.PAY_CHANNEL_HJ.getCode()+"初始化完成");
		return mcamRepaymentTradeDetails;
	}

	/**
	 *
	* @Title: initWithhold
	* @Description:初始化代扣数据
	* @param idno
	* @param bindCard
	* @param amount
	* @param title
	* @param channel
	* @author 李瑶
	* @date 2018年10月11日 下午3:42:47
	 */
	private McfeRepaymentTradeDetails initWithhold(String requestNo,String idno,String bindCard,String amount,String title,String channel )throws MarvelsBusinessException{
		String orderNum = YbPayService.getReuqestNum("yb");

		McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
		McfePaymentUserBindCardCondition.setIdno(idno);
		McfePaymentUserBindCardCondition.setBankCardNo(bindCard);
		McfePaymentUserBindCardCondition.setChannel(channel);
		McfePaymentUserBindCardCondition.setStatus("BIND_SUCCESS");
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = new McfeRepaymentTradeDetails();
		if(mcamPaymentUserBindCard == null && !channel.equals(PayContants.PAY_CHANNEL_HJ.getCode())){
			logger.info("withhold============idno="+idno+",bindCard="+bindCard
					+",amount="+amount+"channel="+channel+"客户尚未绑卡成功");
			throw new MarvelsBusinessException("客户尚未绑卡成功");
		}
		mcamRepaymentTradeDetails.setBankCode(mcamPaymentUserBindCard.getBankCode());
		mcamRepaymentTradeDetails.setCustName(mcamPaymentUserBindCard.getCustName());
		mcamRepaymentTradeDetails.setBankName(mcamPaymentUserBindCard.getBankName());
		mcamRepaymentTradeDetails.setAmount(amount);
		mcamRepaymentTradeDetails.setBankNumber(bindCard);
		mcamRepaymentTradeDetails.setChannel(channel);
		mcamRepaymentTradeDetails.setCreatedBy("sys");
		mcamRepaymentTradeDetails.setCreatedDate(new Date());
		//1代付 2代扣
		mcamRepaymentTradeDetails.setTradeType("2");
		//不发送短信
		mcamRepaymentTradeDetails.setIsSms("1");
		mcamRepaymentTradeDetails.setIdNumber(idno);
		mcamRepaymentTradeDetails.setRequestNo(requestNo);
		mcamRepaymentTradeDetails.setPayOrderNumber(orderNum);
		mcamRepaymentTradeDetails.setUpdatedBy("sys");
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetailsMapper.insertSelective(mcamRepaymentTradeDetails);
		logger.info("withhold============idno="+idno+",bindCard="+bindCard
				+",amount="+amount+"channel="+channel+"初始化完成");
		return mcamRepaymentTradeDetails;
	}


	/**
	 * 宝付代扣初始化
	 * @param requestNo
	 * @param idno
	 * @param bindCard
	 * @param amount
	 * @param title
	 * @param channel
	 * @param orderNumber
	 * @return
	 * @throws MarvelsBusinessException
	 */
	private McfeRepaymentTradeDetails initBfWithhold(String requestNo,String idno,String bindCard,String amount,String title,String channel,String orderNumber)throws MarvelsBusinessException{
		McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
		McfePaymentUserBindCardCondition.setIdno(idno);
		McfePaymentUserBindCardCondition.setBankCardNo(bindCard);
		McfePaymentUserBindCardCondition.setChannel(channel);
		McfePaymentUserBindCardCondition.setStatus("BIND_SUCCESS");
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = new McfeRepaymentTradeDetails();
		if(mcamPaymentUserBindCard == null && !channel.equals(PayContants.PAY_CHANNEL_HJ.getCode())){
			logger.info("withhold============idno="+idno+",bindCard="+bindCard
					+",amount="+amount+"channel="+channel+"客户尚未绑卡成功");
			throw new MarvelsBusinessException("客户尚未绑卡成功");
		}
		mcamRepaymentTradeDetails.setBankCode(mcamPaymentUserBindCard.getBankCode());
		mcamRepaymentTradeDetails.setCustName(mcamPaymentUserBindCard.getCustName());
		mcamRepaymentTradeDetails.setBankName(mcamPaymentUserBindCard.getBankName());
		mcamRepaymentTradeDetails.setAmount(amount);
		mcamRepaymentTradeDetails.setBankNumber(bindCard);
		mcamRepaymentTradeDetails.setChannel(channel);
		mcamRepaymentTradeDetails.setCreatedBy("sys");
		mcamRepaymentTradeDetails.setCreatedDate(new Date());
		//1代付 2代扣
		mcamRepaymentTradeDetails.setTradeType("2");
		//不发送短信
		mcamRepaymentTradeDetails.setIsSms("1");
		mcamRepaymentTradeDetails.setIdNumber(idno);
		mcamRepaymentTradeDetails.setRequestNo(requestNo);
		mcamRepaymentTradeDetails.setPayOrderNumber(orderNumber);
		mcamRepaymentTradeDetails.setUpdatedBy("sys");
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetails.setBindOrderId(mcamPaymentUserBindCard.getBindOrderId());
		mcamRepaymentTradeDetailsMapper.insertSelective(mcamRepaymentTradeDetails);
		logger.info("withhold============idno="+idno+",bindCard="+bindCard
				+",amount="+amount+"channel="+channel+"初始化完成");
		return mcamRepaymentTradeDetails;
	}

	/**
	 *
	* @Title: resolveYbWithholdReturnData
	* @Description:解析代扣返回的数据
	* @param mcamPaymentUserBindCard
	* @param withholdData
	* @author 李瑶
	* @date 2018年10月11日 下午4:06:03
	 */
	private void resolveYbWithholdReturnData(McfeRepaymentTradeDetails mcamRepaymentTradeDetails,Map<String,Object> withholdData){
		String yborderid = (String)withholdData.get("yborderid");
		//PAY_FAIL： 支付失败 PROCESSING： 处理中 TIME_OUT： 超时失败 FAIL： 系统异常

		String status = (String)withholdData.get("status");
		String result = getYbWithholdResult(status);
		String errorcode = (String)withholdData.get("errorcode");
		String errormsg = (String)withholdData.get("errormsg");

		mcamRepaymentTradeDetails.setPayNumReturn(yborderid);
		mcamRepaymentTradeDetails.setResult(result);
		mcamRepaymentTradeDetails.setErrorCode(errorcode);
		mcamRepaymentTradeDetails.setErrorMsg(errormsg);
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);

	}


	/**
	 * 汇聚代扣返回结果解析
	 * @param mcamRepaymentTradeDetails
	 * @param withholdData
	 */
	private void resolveHjWithholdReturnData(McfeRepaymentTradeDetails mcamRepaymentTradeDetails,Map<String,Object> withholdData){
		String hjOrderid = (String)withholdData.get("r5_TrxNo");
		String status = (String)withholdData.get("status");
		String errorcode =(String)withholdData.get("errorcode");
		String errormsg = (String)withholdData.get("errormsg");
		mcamRepaymentTradeDetails.setPayNumReturn(hjOrderid);
		mcamRepaymentTradeDetails.setResult(status);
		mcamRepaymentTradeDetails.setErrorCode(errorcode);
		mcamRepaymentTradeDetails.setErrorMsg(errormsg);
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);

	}

	/**
	 *
	* @Title: getYbWithholdResult
	* @Description: 状态转换
	* @param status
	* @return
	* @author 李瑶
	* @date 2018年10月11日 下午4:46:31
	 */
	private String getYbWithholdResult(String status){
		String result = "";
		if("PROCESSING".equals(status)){
			//处理中
			result = "1";
		}else if("TIME_OUT".equals(status)){
			//超时
			result = "-2";
		}else if("PAY_FAIL".equals(status)){
			//支付失败
			result = "-1";
		}else if("FAIL".equals(status)){
			//系统异常
			result = "-4";
		}else if("PAY_SUCCESS".equals(status)){
			//支付成功
			result = "0";
		}else{
			result = "-3";
		}
		return result;
	}

	/**
	 *
	* @Title: WithholdCallback
	* @Description: 代扣回调
	* @param param
	* @author 李瑶
	* @date 2018年10月11日 上午9:54:53
	 */
	@Override
	public String WithholdCallback(Map<String, String> param,String channel){
		String merchantno = param.get("merchantno");
		String requestno = param.get("requestno");
		String yborderid = param.get("yborderid");
		String amount = param.get("amount");
		String status = param.get("status");
		String errorcode = param.get("errorcode");
		String errormsg = param.get("errormsg");
		if(StringUtils.isEmpty(yborderid) || StringUtils.isEmpty(requestno)){
			return "FAIL";
		}
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByRequestNo(requestno);
		if(mcamRepaymentTradeDetails == null){
			//数据都查询不到，直接告诉易宝成功，后续这笔单就不用继续处理
			return "SUCCESS";
		}
		String result = getYbWithholdResult(status);
		if("0".equals(result)){
			mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
		}
		mcamRepaymentTradeDetails.setPayOrderNumber(yborderid);
		mcamRepaymentTradeDetails.setResult(getYbWithholdResult(status));
		mcamRepaymentTradeDetails.setErrorCode(errorcode);
		mcamRepaymentTradeDetails.setErrorMsg(errormsg);
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
		return "SUCCESS";
	}

	/**
	 *
	* @Title: queryWithholdResult
	* @Description: 查询代扣结果
	* @param requestNo 易宝编号
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:24:45
	 */
	@Override
	public MarvelsPayResultDTO queryWithholdResult(String orderNum,String channel,String payType){
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByOrderNum(orderNum);
		if(mcamRepaymentTradeDetails == null){
			return MarvelsPayResultDTO.getFailResult("-1", "未查询到该单号的请求数据");
		}
		String result = mcamRepaymentTradeDetails.getResult();
		if("0".equals(result) || "-3".equals(result) || "-4".equals(result) || "-1".equals(result)){
			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
		}
		try {
			if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_HJ.getCode().toUpperCase())){
				Map<String, Object> map=new HashMap<String, Object>();
				if(orderNum.contains("HJXYDK")){//汇聚协议订单号前缀
					AgreementPaymentQueryDTO agreementPaymentQueryDTO=new AgreementPaymentQueryDTO();
					agreementPaymentQueryDTO.setP2_OrderNo(orderNum);
					map=hjPayApi.agreementPaymentQuery(agreementPaymentQueryDTO);
				}else{
					DirectPaymentQueryDTO directPaymentQueryDTO =new DirectPaymentQueryDTO();
					directPaymentQueryDTO.setP2_OrderNo(orderNum);
					map=hjPayApi.directPaymentQuery(directPaymentQueryDTO);
				}
				String status=(String)map.get("status");
				if(StringUtils.isNotEmpty(status) && status.equals("0")){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_HJ.getCode());
				mcamRepaymentTradeDetails.setPayNumReturn((String)map.get("r5_TrxNo"));
				mcamRepaymentTradeDetails.setResult((String)map.get("status"));
				mcamRepaymentTradeDetails.setErrorCode((String)map.get("errorcode"));
				mcamRepaymentTradeDetails.setErrorMsg((String)map.get("errormsg"));
			}
			else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_BF.getCode().toUpperCase())){//宝付通道
				Map<String, Object> map=new HashMap<String, Object>();
				BaoFuDirectPaymentQueryDTO paymentQueryDTO =new BaoFuDirectPaymentQueryDTO();
				paymentQueryDTO.setOrderNumber(orderNum);
				MarvelsLogUtil.getInstance().info("payType:"+payType);
				if("100".equals(payType)){
					map=bfPayApi.baoFuTransPaymentQuery(paymentQueryDTO);
				}else{
					map=bfPayApi.baoFuDirectPaymentQuery(paymentQueryDTO);
				}
				String status=(String)map.get("status");
				if(StringUtils.isNotEmpty(status) && status.equals("0")){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_BF.getCode());
				mcamRepaymentTradeDetails.setPayNumReturn((String)map.get("r5_TrxNo"));
				mcamRepaymentTradeDetails.setResult((String)map.get("status"));
				mcamRepaymentTradeDetails.setErrorCode((String)map.get("errorcode"));
				mcamRepaymentTradeDetails.setErrorMsg((String)map.get("errormsg"));
			}else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_KQ.getCode().toUpperCase())){//快钱通道
//				Map<String, Object> map=new HashMap<String, Object>();
//				KqDirectPaymentQueryDTO kqDirectPaymentQueryDTO =new KqDirectPaymentQueryDTO();
//				kqDirectPaymentQueryDTO.setExternalRefNumber(orderNum);
//				map = kqPayApi.kuaiQianDirectPaymentQuery(kqDirectPaymentQueryDTO);
//				String status=(String)map.get("status");
//				if(StringUtils.isNotEmpty(status) && status.equals("0")){
//					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
//				}
//				mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_KQ.getCode());
//				mcamRepaymentTradeDetails.setPayNumReturn(map.get("r5_TrxNo") == null ? null : (String)map.get("r5_TrxNo"));
//				mcamRepaymentTradeDetails.setResult(map.get("status") == null ? null : (String)map.get("status"));
//				mcamRepaymentTradeDetails.setErrorCode(map.get("errorcode") == null ? null : (String)map.get("errorcode"));
//				mcamRepaymentTradeDetails.setErrorMsg(map.get("errormsg") == null ? null :(String)map.get("errormsg"));
			} else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_CJ.getCode().toUpperCase())){//畅捷通道

				Map<String, Object> map=new HashMap<String, Object>();
				com.marvels.financial.pay.cjpay.dto.DirectPaymentQueryDTO directPaymentQueryDTO = new com.marvels.financial.pay.cjpay.dto.DirectPaymentQueryDTO();
				directPaymentQueryDTO.setOrderTrxId(orderNum);
				directPaymentQueryDTO.setTradeType("pay_order");
				map = cjPayApi.directPaymentQuery(directPaymentQueryDTO);
				String status = (String)map.get("status");
				if(StringUtils.isNotEmpty(status) && status.equals("0")){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_CJ.getCode());
				mcamRepaymentTradeDetails.setPayNumReturn(map.get("r5_TrxNo") == null ? null : (String)map.get("r5_TrxNo"));
				mcamRepaymentTradeDetails.setResult(map.get("status") == null ? null : (String)map.get("status"));
				mcamRepaymentTradeDetails.setErrorCode(map.get("errorcode") == null ? null : (String)map.get("errorcode"));
				mcamRepaymentTradeDetails.setErrorMsg(map.get("errormsg") == null ? null :(String)map.get("errormsg"));

			}else if(orderNum.toUpperCase().endsWith(PayContants.PAY_CHANNEL_YB.getCode().toUpperCase())){
				//易宝渠道
				Map<String, Object> whitholdResult = YbPayService.queryWithholdResult(orderNum, "");
				String yborderid = (String)whitholdResult.get("yborderid");
				String status = (String)whitholdResult.get("status");
				String errorcode = (String)whitholdResult.get("errorcode");
				String errormsg = (String)whitholdResult.get("errormsg");
				String banksuccessdate = (String)whitholdResult.get("banksuccessdate");
				String resultNew = getYbWithholdResult(status);
				mcamRepaymentTradeDetails.setPayNumReturn(yborderid);
				mcamRepaymentTradeDetails.setResult(resultNew);
				mcamRepaymentTradeDetails.setErrorCode(errorcode);
				mcamRepaymentTradeDetails.setErrorMsg(errormsg);
				mcamRepaymentTradeDetails.setSuccessTime(banksuccessdate);
				mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_YB.getCode());

			}
			mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>结果查询失败",e);
			return MarvelsPayResultDTO.getFailResult("-1", e.getMessage());
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>结果查询异常",e);
			return MarvelsPayResultDTO.getFailResult("-1", "结果查询异常");
		}
	}

	/**
	 *
	* @Title: pay
	* @Description:代发
	* @param param 代发入参
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:26:34
	 */
	@Override
	public MarvelsPayResultDTO pay(Map<String, String> param,String channel){
			if(PayContants.PAY_CHANNEL_YZF.getCode().equals(channel)) {
				String yzfOrderNo=GenerateReqNoUtils.transctionReq2("YZFPAY",24);
				McfeRepaymentTradeDetails detail = initPayInfo(param, channel,yzfOrderNo);
				MarvelsPayResultDTO resultDto = new MarvelsPayResultDTO();
				resultDto.setCode("0");
				String accountName = param.get("accountName");
				String bankCardNo = param.get("bankCardNo");
				String bankName = param.get("bankName");
				String amount = param.get("amount");
				PayResultDto payresultDto = yzfPayService.signalPay(yzfOrderNo, amount, accountName, bankCardNo, bankName, "");
				if(StringUtils.equalsIgnoreCase(payresultDto.getPayStatus(), PayStatusEnum.FAIL.toString())) {
					resultDto.setCode("-1");
					resultDto.setMessage(payresultDto.getRespMsg());
					resultDto.setData(payresultDto);
				}
				try {
					detail.setErrorCode(payresultDto.getPayStatus());
					detail.setErrorMsg(payresultDto.getRespMsg());
					String respContent = payresultDto.getRespContent();
					if(2600 < StringUtils.length(payresultDto.getRespContent())) {
						respContent = respContent.substring(0, 2600);
					}
					detail.setRespContent(respContent);
					detail.setPayNumReturn(payresultDto.getPayChannelOrderNo());
					MarvelsLogUtil.getInstance().info("modify trade details start param==>"+JSON.toJSONString(detail));
					mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(detail);
				}catch(Exception ex) {
					MarvelsLogUtil.getInstance().error("pay result Error param==>",ex);
				}
				resultDto.setData(detail);
				return resultDto;
			}else if(PayContants.PAY_CHANNEL_BF.getCode().equals(channel)){
			String bfOrderNo=GenerateReqNoUtils.transctionReq2("BFPAY",24);
			McfeRepaymentTradeDetails detail = initPayInfo(param, channel,bfOrderNo);
			MarvelsPayResultDTO resultDto = new MarvelsPayResultDTO();
			resultDto.setCode("0");
			String accountName = param.get("accountName");
			String bankCardNo = param.get("bankCardNo");
			String bankName = param.get("bankName");
			String amount = param.get("amount");
			String idno = param.get("idno");
			BaoFuPayTradeDTO baoFuPayTradeDTO = new BaoFuPayTradeDTO();
			baoFuPayTradeDTO.setOrderNumber(bfOrderNo);
			baoFuPayTradeDTO.setToAccName(accountName);
			baoFuPayTradeDTO.setToAccNo(bankCardNo);
			baoFuPayTradeDTO.setToBankName(bankName);
			baoFuPayTradeDTO.setTransMoney(amount);
			baoFuPayTradeDTO.setTransCardId(idno);
            try {
				PayResultDto payresultDto = bfPayApi.baoFuPayTrade(baoFuPayTradeDTO);
				if(StringUtils.equalsIgnoreCase(payresultDto.getPayStatus(), PayStatusEnum.FAIL.toString())) {
					resultDto.setCode("-1");
					resultDto.setMessage(payresultDto.getRespMsg());
					resultDto.setData(payresultDto);
				}
//				try {
					detail.setErrorCode(payresultDto.getPayStatus());
					detail.setErrorMsg(payresultDto.getRespMsg());
					String respContent = payresultDto.getRespContent();
					detail.setRespContent(respContent);
					detail.setPayNumReturn(payresultDto.getPayChannelOrderNo());
					MarvelsLogUtil.getInstance().info("modify trade details start param==>"+JSON.toJSONString(detail));
					mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(detail);
				}catch(Exception ex) {
					MarvelsLogUtil.getInstance().error("pay result Error param==>",ex);
				}
				resultDto.setData(detail);
				return resultDto;

//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
			}
			else {
				return MarvelsPayResultDTO.getFailResult("-1", "未知的支付渠道");
			}
	}


	private MarvelsPayResultDTO resolveYbPayReturnData(McfeRepaymentTradeDetails mcamRepaymentTradeDetails,Map<String,Object> payResult){
		MarvelsPayResultDTO marvelsResultDTO = new MarvelsPayResultDTO();

		String errorCode = (String)payResult.get("errorCode");
		String errorMsg = (String)payResult.get("errorMsg");
		String orderId = (String)payResult.get("orderId");
		String batchNo = (String)payResult.get("batchNo");
		//0025 打款结果： 已接收,0026 打款结果： 已汇出 ,0027 打款结果： 已退款, 0028 打款结果： 已拒绝 ,0029打款结果： 待复核, 0030 打款结果:未知
		//这个接口返回的状态并没有什么卵用，还要看后面返回的结果确认状态
		String transferStatusCode = (String)payResult.get("transferStatusCode");
		mcamRepaymentTradeDetails.setErrorCode(errorCode);
		mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
		mcamRepaymentTradeDetails.setPayNumReturn(orderId);
		mcamRepaymentTradeDetails.setPayBatchId(batchNo);
		if(StringUtils.isNotEmpty(transferStatusCode)){
			//有返回状态位，则标志易宝已经收到请求，并且已经发送到银行
			mcamRepaymentTradeDetails.setResult("1");
			marvelsResultDTO.setCode("0");
			marvelsResultDTO.setMessage("请求成功");
		}else{
			//请求中，易宝返回了错误
			mcamRepaymentTradeDetails.setResult("-4");
			marvelsResultDTO.setCode(PayContants.PAY_REQUEST_ERROR.getCode());
			marvelsResultDTO.setMessage(errorMsg);
		}
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		marvelsResultDTO.setData(mcamRepaymentTradeDetails);
		mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
		return marvelsResultDTO;
	}

	/**
	 * 汇聚代付结果处理
	 * @param mcamRepaymentTradeDetails
	 * @param payResult
	 * @return
	 */
	private MarvelsPayResultDTO resolveHjPayReturnData(McfeRepaymentTradeDetails mcamRepaymentTradeDetails,Map<String,Object> payResult){
		MarvelsPayResultDTO marvelsResultDTO = new MarvelsPayResultDTO();
		String errorCode = (String)payResult.get("errorCode");
		String errorMsg = (String)payResult.get("errormsg");
		//0025 打款结果： 已接收,0026 打款结果： 已汇出 ,0027 打款结果： 已退款, 0028 打款结果： 已拒绝 ,0029打款结果： 待复核, 0030 打款结果:未知
		//这个接口返回的状态并没有什么卵用，还要看后面返回的结果确认状态
		mcamRepaymentTradeDetails.setErrorCode(errorCode);
		mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
		mcamRepaymentTradeDetails.setResult("1");
		mcamRepaymentTradeDetails.setUpdatedDate(new Date());
		marvelsResultDTO.setCode("0");
		marvelsResultDTO.setMessage("请求成功");
		marvelsResultDTO.setData(mcamRepaymentTradeDetails);
		mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
		return marvelsResultDTO;
	}

	/**
	 *
	* @Title: initPayInfo
	* @Description:初始化打款信息
	* @return
	* @author 李瑶
	* @date 2018年10月11日 下午7:35:30
	 */
	private McfeRepaymentTradeDetails initPayInfo(Map<String, String> param,String channel,String orderId){
		//batchNumber, orderNumber, amount, accountName, bankCardNo, bankCode, bankName,
		//bankBranchName, provinceCode, cityCode, feeType
		Date date = new Date();

		String payBatchId = YbPayService.getBatchId();

		//待付不用传requestno,将requestno设置为要传过去的orderid（吐槽：么屁支付接口，代扣和代付的处理方式还不同，接口文档还弄两套）
		String requestNo = param.get("requestNo");
		String idno = param.get("idno");
		String amount = param.get("amount");
		String accountName = param.get("accountName");
		String bankCardNo = param.get("bankCardNo");
		String bankName = param.get("bankName");
		String bankBranchName = param.get("bankBranchName");
		String provinceCode = param.get("provinceCode");
		String cityCode = param.get("cityCode");
		String feeType = param.get("feeType");
		String hlbUserId = param.get("hlbUserId");
		String mobileNo = param.get("mobileNo");

		String bankCode = getBankCode(idno, bankCardNo);
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = new McfeRepaymentTradeDetails();
		mcamRepaymentTradeDetails.setAmount(amount);
		mcamRepaymentTradeDetails.setBankNumber(bankCardNo);
		mcamRepaymentTradeDetails.setBankCode(bankCode);
		mcamRepaymentTradeDetails.setBankBranchName(bankBranchName);
		mcamRepaymentTradeDetails.setBankName(bankName);
		mcamRepaymentTradeDetails.setChannel(channel);
		mcamRepaymentTradeDetails.setCityCode(cityCode);
		mcamRepaymentTradeDetails.setCreatedBy("sys");
		mcamRepaymentTradeDetails.setCreatedDate(date);
		mcamRepaymentTradeDetails.setCustName(accountName);
		mcamRepaymentTradeDetails.setFeeType(feeType);
		mcamRepaymentTradeDetails.setIdNumber(idno);
		mcamRepaymentTradeDetails.setIsSms("1");
		mcamRepaymentTradeDetails.setPayBatchId(payBatchId);
		mcamRepaymentTradeDetails.setPayOrderNumber(orderId);
		mcamRepaymentTradeDetails.setProvinceCode(provinceCode);
		mcamRepaymentTradeDetails.setRequestNo(requestNo);
		mcamRepaymentTradeDetails.setUpdatedBy("sys");
		mcamRepaymentTradeDetails.setUpdatedDate(date);
		mcamRepaymentTradeDetails.setTradeType("1");
		mcamRepaymentTradeDetails.setHlbUserId(hlbUserId);
		mcamRepaymentTradeDetails.setMobileNo(mobileNo);
		mcamRepaymentTradeDetailsMapper.insertSelective(mcamRepaymentTradeDetails);
		return mcamRepaymentTradeDetails;
	}


	/**
	 * 汇聚代扣初始化参数
	 * @param param
	 * @param orderNUmber
	 * @return
	 */
	private McfeRepaymentTradeDetails hjInitPayInfo(Map<String, String> param,String orderNUmber){
		//batchNumber, orderNumber, amount, accountName, bankCardNo, bankCode, bankName,
		//bankBranchName, provinceCode, cityCode, feeType
		Date date = new Date();
		//待付不用传requestno,将requestno设置为要传过去的orderid（吐槽：么屁支付接口，代扣和代付的处理方式还不同，接口文档还弄两套）
		String requestNo = param.get("requestNo");
		String idno = param.get("idno");
		String amount = param.get("amount");
		String accountName = param.get("accountName");
		String bankCardNo = param.get("bankCardNo");
		String bankName = param.get("bankName");
		String bankBranchName = param.get("bankBranchName");
		String provinceCode = param.get("provinceCode");
		String cityCode = param.get("cityCode");
		String feeType = param.get("feeType");
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = new McfeRepaymentTradeDetails();
		mcamRepaymentTradeDetails.setAmount(amount);
		mcamRepaymentTradeDetails.setBankNumber(bankCardNo);
		mcamRepaymentTradeDetails.setBankBranchName(bankBranchName);
		mcamRepaymentTradeDetails.setBankName(bankName);
		mcamRepaymentTradeDetails.setChannel(PayContants.PAY_CHANNEL_HJ.getCode());
		mcamRepaymentTradeDetails.setCityCode(cityCode);
		mcamRepaymentTradeDetails.setCreatedBy("sys");
		mcamRepaymentTradeDetails.setCreatedDate(date);
		mcamRepaymentTradeDetails.setCustName(accountName);
		mcamRepaymentTradeDetails.setFeeType(feeType);
		mcamRepaymentTradeDetails.setIdNumber(idno);
		mcamRepaymentTradeDetails.setPayOrderNumber(orderNUmber);
		mcamRepaymentTradeDetails.setProvinceCode(provinceCode);
		mcamRepaymentTradeDetails.setRequestNo(requestNo);
		mcamRepaymentTradeDetails.setUpdatedBy("sys");
		mcamRepaymentTradeDetails.setUpdatedDate(date);
		mcamRepaymentTradeDetails.setTradeType("1");
		mcamRepaymentTradeDetailsMapper.insertSelective(mcamRepaymentTradeDetails);
		return mcamRepaymentTradeDetails;
	}

	private String getBankCode(String idno,String bankCardNo){
		McfePaymentUserBindCardCondition mfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
		mfePaymentUserBindCardCondition.setIdno(idno);
		mfePaymentUserBindCardCondition.setBankCardNo(bankCardNo);
		mfePaymentUserBindCardCondition.setChannel(PayContants.PAY_CHANNEL_YB.getCode());
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(mfePaymentUserBindCardCondition);
		if(mcamPaymentUserBindCard == null){
			logger.info("getBankCode============idno="+idno+",bindCard="+bankCardNo+"查询银行编号");
			return null;
		}
		String bankCode = mcamPaymentUserBindCard.getBankCode();
		if(StringUtils.isEmpty(bankCode)){
			Map<String,Object> returnMap = YbPayService.queryBindCardRecord(mcamPaymentUserBindCard.getRequestNo(), "");
			if(returnMap != null){
				bankCode = (String)returnMap.get("bankcode");
				mcamPaymentUserBindCard.setBankCode(bankCode);
				mcamPaymentUserBindCardMapper.updateByPrimaryKeySelective(mcamPaymentUserBindCard);
			}
		}
		return bankCode;
	}

	/**
	 *
	* @Title: queryPayResult
	* @Description:查询代发结果
	* @param orderNum 订单号
	* @param channel 渠道 yb 易宝  后续渠道可进行拓
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:27:00
	 */
	@Override
	public MarvelsPayResultDTO queryPayResult(String orderNum,String channel){
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByOrderNum(orderNum);
		if(mcamRepaymentTradeDetails == null){
			return MarvelsPayResultDTO.getFailResult("-1", "未查询到该单号的请求数据");
		}
		String result = mcamRepaymentTradeDetails.getResult();
		if("0".equals(result) || "-3".equals(result) || "-4".equals(result) || "-1".equals(result)){
			//已经标注为成功或者失败，则不需要重复去查询易宝接口查询状态
			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
		}
		try {
			if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_HJ.getCode().toUpperCase())){
				SinglePaymentQueryDTO singlePaymentQueryDTO=new SinglePaymentQueryDTO();
				singlePaymentQueryDTO.setMerchantOrderNo(orderNum);
				Map<String, Object> payResult = hjPayApi.singlePaymentQuery(singlePaymentQueryDTO);
				String errorCode = (String)payResult.get("errorCode");
				String errorMsg = (String)payResult.get("errormsg");
				String statusReturn =  (String)payResult.get("status");
				if("0".equals(statusReturn)){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setResult(statusReturn);
				mcamRepaymentTradeDetails.setUpdatedDate(new Date());
				mcamRepaymentTradeDetails.setErrorCode(errorCode);
				mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
			}
			else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_BF.getCode().toUpperCase())){
				BaoFuPayTradeStrtusQueryDTO queryDTO=new BaoFuPayTradeStrtusQueryDTO();
				queryDTO.setOrignOrderNumber(orderNum);
				Map<String, Object> payResult = bfPayApi.baoFuPayTradeStrtusQuery(queryDTO);
				String errorCode = (String)payResult.get("errorCode");
				String errorMsg = (String)payResult.get("errormsg");
				String statusReturn =  (String)payResult.get("status");
				if("0".equals(statusReturn)){
					mcamRepaymentTradeDetails.setSuccessTime(DateUtils.getDateStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
				}
				mcamRepaymentTradeDetails.setResult(statusReturn);
				mcamRepaymentTradeDetails.setUpdatedDate(new Date());
				mcamRepaymentTradeDetails.setErrorCode(errorCode);
				mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
			}else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_KQ.getCode().toUpperCase())){
//				Map<String, Object> payResult = new HashMap<String, Object>();
//				payResult=kqPayApi.payResultQuery(mcamRepaymentTradeDetails);
//				String errorCode = (String)payResult.get("errorCode");
//				String errorMsg = (String)payResult.get("errorMsg");
//				mcamRepaymentTradeDetails.setResult(payResult.get("result").toString());
//				mcamRepaymentTradeDetails.setErrorCode(errorCode);
//				mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
			}else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_CJ.getCode().toUpperCase())){
				Map<String, Object> payResult = new HashMap<String, Object>();
				payResult=cjPayApi.payResultQuery(mcamRepaymentTradeDetails);
				String errorCode = (String)payResult.get("errorCode");
				String errorMsg = (String)payResult.get("errorMsg");
				mcamRepaymentTradeDetails.setResult(payResult.get("result").toString());
				mcamRepaymentTradeDetails.setErrorCode(errorCode);
				mcamRepaymentTradeDetails.setErrorMsg(errorMsg);
			}else if(orderNum.toUpperCase().startsWith(PayContants.PAY_CHANNEL_YZF.getCode().toUpperCase())) {
				PayResultDto payResultDto = yzfPayService.signalPayQuery(mcamRepaymentTradeDetails.getPayOrderNumber());
				mcamRepaymentTradeDetails.setResult(payResultDto.getPayStatus());
				mcamRepaymentTradeDetails.setErrorCode(payResultDto.getRespCode());
				mcamRepaymentTradeDetails.setErrorMsg(payResultDto.getRespMsg());
			}
			try {
				mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
			}catch(Exception ex) {
				MarvelsLogUtil.getInstance().error(">>>>>>>>>>>orderNum:" +orderNum + "更新查询结果是把:", ex);
			}

			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
		}catch (MarvelsBusinessException e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>orderNum:" +orderNum + "代付结果查询失败:", e);
			return MarvelsPayResultDTO.getFailResult("-1",e.getMessage());
		}catch (Exception e) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>orderNum:" + orderNum + "代付结果查询异常:", e);
			return MarvelsPayResultDTO.getFailResult("-1", "代发结果查询异常");
		}
	}

	/**
	 *
	* @Title: getBankCardInfo
	* @Description:查询银行卡信息
	* @param bindId
	* @param channel
	* @return
	* @author 李瑶
	* @date 2018年11月2日 下午5:31:12
	 */
	@Override
	public MarvelsPayResultDTO getBankCardInfo(String bankCardNo,String channel){
		Map<String, Object> map = new HashMap<>();
		if(PayContants.PAY_CHANNEL_YB.getCode().equals(channel)){
			map = YbPayService.queryBankCardInfo(bankCardNo);
		}
		if(PayContants.PAY_CHANNEL_HJ.getCode().equals(channel) || PayContants.PAY_CHANNEL_BF.getCode().equals(channel) || PayContants.PAY_CHANNEL_KQ.getCode().equals(channel)){
			McfeCardBinInfoDTO infoDTO= mcfeCardBinInfoDao.selectByBankCard(bankCardNo);
			if(infoDTO != null){
				map.put("bankname",infoDTO.getBankName());
			}
		}
		return MarvelsPayResultDTO.getSuccessResult(map);
	}


	/**
	 *
	* @Title: payResultCallback
	* @Description:支付结果回调
	* @param param
	* @param channel
	* @return
	* @author 李瑶
	* @date 2018年10月12日 上午11:08:57
	 */
	@Override
	public String payResultCallback(Map<String, String> param,String channel){
		PayResultDto payResultDto = yzfPayService.payResultCallBackPase(param.get("param"));
		if(StringUtils.isBlank(payResultDto.getPlatformOrderNo())) {
			return null;
		}
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = mcamRepaymentTradeDetailsMapper.selectByOrderNum(payResultDto.getPlatformOrderNo());
		if(mcamRepaymentTradeDetails == null){
			return null;
		}
//
//		//记录放款日志
//		loanAuditApi.auditCommonDeal(loanId, auditStatus, mcfeLendingProcess.getStatus(), "放款查询", null);
//
//				// 持久化审核信息
//				McfeLendingProcess process = new McfeLendingProcess();
//				process.setLoanId(loanId);
//				process.setOrderNumber(orderNumber);
//				int index = StringUtils.indexOf(mcfeLendingProcess.getMsg(), "#");
//				if(-1 != index) {
//					process.setMsg(StringUtils.substring(mcfeLendingProcess.getMsg(), 0, index));
//				}
//				process.setMsg(mcfeLendingProcess.getMsg() + "#" + auditMsg);
//				process.setStatus(auditStatus);
//				if("F2".equals(auditStatus)){
//					//自动放款成功
//					process.setPassTime(new Date());
//					//新增 ac_loan_apply_info 	money_hand_out_uid
//					try {
//						String reloanFlag =  consumerLoanApplyApi.synchroMoneyHandOutTime(loanId);
//						process.setReloanFlag(reloanFlag);
//					} catch (Exception e) {
//						MarvelsLogUtil.getInstance().error(">>>>>>>>>>loanId:" + loanId + "同步到进件表的放款时间失败:", e);
//					}
//				}
//				process.setUpdatedBy("system");
//				process.setOriginalStatus(mcfeLendingProcess.getStatus());
//				process.setLoanId(loanId);
//				process.setIsBusy("0");// 将审核状态改为空闲
//				int countInsert = mcfeLendingProcessMapper.updateAuditResult(process);
//				if (countInsert < 1) {
//					MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>loanId" + loanId + ",持久化审核信息失败");
//					throw new MarvelsBusinessException("代付结果查询持久化审核信息失败");
//				}

		mcamRepaymentTradeDetails.setResult(payResultDto.getPayStatus());
		mcamRepaymentTradeDetails.setErrorCode(payResultDto.getRespCode());
		mcamRepaymentTradeDetails.setErrorMsg(payResultDto.getRespMsg());
		try {
			mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
		}catch(Exception ex) {
			MarvelsLogUtil.getInstance().error(">>>>>>>>>>>orderNum:" +payResultDto.getPlatformOrderNo() + "更新回调通知:", ex);
		}

		return "SUCESS";
	}

	/**
	 *
	* @Title: queryBindCardInfoById
	* @Description: 根据绑卡ID主键查询用户的绑卡信息
	* @param bindId 绑卡主键ID
	* @return
	* @author 李瑶
	* @date 2018年10月10日 下午3:16:28
	 */
	@Override
	public MarvelsPayResultDTO queryBindCardInfoById(long bindId){
		McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByPrimaryKey(bindId);
		logger.info("queryBindedList============result："+JSON.toJSONString(mcamPaymentUserBindCard));
		return MarvelsPayResultDTO.getSuccessResult(mcamPaymentUserBindCard);
	}

	/**
	 *
	* @Title: getPayResultStatus
	* @Description:
	* @param bankTrxStatusCode
	* @return
	* @author 李瑶
	* @date 2018年10月12日 上午11:23:25
	 */
	private String getPayResultStatus(String bankTrxStatusCode){
		String result = "";
		if("S".equals(bankTrxStatusCode)){
			//银行代发成功
			result = "0";
		}else if("I".equals(bankTrxStatusCode) || "W".equals(bankTrxStatusCode) || "U".equals(bankTrxStatusCode)){
			//银行处理中
			result = "1";
		}else if("F".equals(bankTrxStatusCode)){
			//银行代发失败
			result = "-1";
		}else{
			//支付公司返回异常
			result = "-4";
		}
		return result;
	}


	@Override
	public MarvelsPayResultDTO merchantRecharge(MerchantRechargeDTO merchantRechargeDTO) throws MarvelsBusinessException{
		Map<String, Object> map=new HashMap<String, Object>();
		if(merchantRechargeDTO.getRechargeAmount()==null){
			throw new MarvelsBusinessException("充值金额不能为空");
		}
		if(StringUtils.isEmpty(merchantRechargeDTO.getRechargeChannel())){
			throw new MarvelsBusinessException("充值渠道不能为空");
		}
		String orderNo=GenerateReqNoUtils.transctionReq2("HJWXCZ",24);
		initMerchantRechargeData(merchantRechargeDTO.getRechargeAmount(),orderNo,merchantRechargeDTO.getRechargeChannel());
		if(merchantRechargeDTO.getRechargeChannel().equals(PayContants.PAY_CHANNEL_HJ.getCode())){//汇聚充值
			MerchantRechargePayDTO merchantRechargePayDTO=new MerchantRechargePayDTO();
			merchantRechargePayDTO.setP2_OrderNo(orderNo);
			merchantRechargePayDTO.setP3_Amount(merchantRechargeDTO.getRechargeAmount());
			merchantRechargePayDTO.setP5_ProductName("商户充值");
			map=hjPayApi.merchantRecharge(merchantRechargePayDTO);
		}
		return MarvelsPayResultDTO.getSuccessResult(map);
	}


	/**
	 * 初始化充值记录
	 * @param amount
	 * @param orderNo
	 * @param rechargeChannel
	 */
	private void initMerchantRechargeData(BigDecimal amount,String orderNo,String rechargeChannel){
		McfeMerchantRechargeRecordDTO mcfeMerchantRechargeRecordDTO=new McfeMerchantRechargeRecordDTO();
		mcfeMerchantRechargeRecordDTO.setAmount(amount);
		mcfeMerchantRechargeRecordDTO.setChannel(rechargeChannel);
		UserDTO user=null;
		try {
			user = CacheUtils.getCacheUser();
		} catch (MarvelsBusinessException e) {

		}
		String userCode=user==null?"system":user.getUserCode();
		mcfeMerchantRechargeRecordDTO.setCreatedBy(userCode);
		mcfeMerchantRechargeRecordDTO.setCreatedDate(new Date());
		mcfeMerchantRechargeRecordDTO.setOrderNumber(orderNo);
		mcfeMerchantRechargeRecordDTO.setUpdatedBy(userCode);
		mcfeMerchantRechargeRecordDTO.setUpdatedDate(new Date());
		mcfeMerchantRechargeRecordMapper.insertSelective(mcfeMerchantRechargeRecordDTO);
	}


	@Override
	public MarvelsPayResultDTO merchantBalance(MerchantRechargeDTO merchantRechargeDTO) throws MarvelsBusinessException{
		if(StringUtils.isEmpty(merchantRechargeDTO.getRechargeChannel())){
			throw new MarvelsBusinessException("充值渠道不能为空");
		}
		Map<String, Object> map=new HashMap<String, Object>();
		if(merchantRechargeDTO.getRechargeChannel().equals(PayContants.PAY_CHANNEL_HJ.getCode())){//汇聚查询
			map=hjPayApi.merchantBalance();
		}
		return MarvelsPayResultDTO.getSuccessResult(map);
	}


	@Override
	public Page<McfeMerchantRechargeRecordDTO> merchantRechargeRecord(
			McfeMerchantRechargeRecordDTO mcfeMerchantRechargeRecordDTO) throws MarvelsBusinessException {
		if(mcfeMerchantRechargeRecordDTO.getPageNum()==null){
			mcfeMerchantRechargeRecordDTO.setPageNum(PageConstant.CURRPAGE);
		}
		if(mcfeMerchantRechargeRecordDTO.getPageSize()==null){
			mcfeMerchantRechargeRecordDTO.setPageSize(PageConstant.PAGESIZE);
		}
		PageHelper.startPage(mcfeMerchantRechargeRecordDTO.getPageNum(), mcfeMerchantRechargeRecordDTO.getPageSize());
		Page<McfeMerchantRechargeRecordDTO> list=mcfeMerchantRechargeRecordMapper.selectList(mcfeMerchantRechargeRecordDTO);
		return list;
	}


	@Override
	public MarvelsPayResultDTO bankBindList(Map<String, Object> param) throws MarvelsBusinessException{
		//先判断当前当前还款通道时候绑卡
		String idno = (String)param.get("idno");
		if(StringUtils.isEmpty(idno)){
			throw new MarvelsBusinessException("身份证不能为空");
		}
		//先判断当前支付是否存在绑卡列表
		String channel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
		List<McfePaymentUserBindCard> bindCards = mcamPaymentUserBindCardMapper.selectBindSuccessListByIdno(idno, channel);
		String isBind="0";//默认未绑卡
		if(bindCards!=null && bindCards.size()>0){
			isBind="1";//已绑卡
		}

		if(isBind.equals("0")){//未绑卡 则返回之前通道绑卡列表
			bindCards = new ArrayList<McfePaymentUserBindCard>();
			McfePaymentUserBindCard mcfePaymentUserBindCard=new McfePaymentUserBindCard();
			mcfePaymentUserBindCard.setIdno(idno);
			mcfePaymentUserBindCard=mcamPaymentUserBindCardMapper.selectBindCard(mcfePaymentUserBindCard);
			bindCards.add(mcfePaymentUserBindCard);
		}
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("isBind",isBind);
		map.put("bindCard",bindCards);
		return MarvelsPayResultDTO.getSuccessResult(map);
	}


	@Override
	public MarvelsPayResultDTO withhold(WithholdConditionDTO conditionDTO) {
		String idno=conditionDTO.getIdno();
		String bindCard=conditionDTO.getBindCard();
		String amount=conditionDTO.getAmount();
		String channel=conditionDTO.getChannel();
		String requestNo=conditionDTO.getRequestNo();
		String title=conditionDTO.getTitle();
		String type=conditionDTO.getType();
		logger.info("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"type="+type+"开始");
		McfeRepaymentTradeDetails mcamRepaymentTradeDetails = null;
		try {
			logger.info("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"开始发送端口请求");
			if(PayContants.PAY_CHANNEL_YB.getCode().equals(channel)){
				mcamRepaymentTradeDetails = initWithhold(requestNo,idno, bindCard, amount, title, channel);
				Map<String, Object> payResult = YbPayService.withhold("1", mcamRepaymentTradeDetails.getPayOrderNumber(), idno, bindCard, amount, title);
				resolveYbWithholdReturnData(mcamRepaymentTradeDetails, payResult);
			}
			if(PayContants.PAY_CHANNEL_HJ.getCode().equals(channel)){//汇聚通道
				String orderNo=GenerateReqNoUtils.transctionReq2("HJXYDK",24);
				if("1".equals(type)){
					//直接代扣的订单号和金额需要和直接短信接口的订单号和金额一致
					McfeRepaymentTradeDetails details=new McfeRepaymentTradeDetails();
					details.setCustName(conditionDTO.getCustName());
					details.setIdNumber(idno);
					details.setBankNumber(bindCard);
					details.setMobileNo(conditionDTO.getMobile());
					details.setAmount(amount);
					mcamRepaymentTradeDetails =mcamRepaymentTradeDetailsMapper.selectTradeInfo(details);
					if(mcamRepaymentTradeDetails==null){
						return MarvelsPayResultDTO.getFailResult("-1", "快捷支付短信调用信息不存在");
					}
					DirectPaymentDTO dDirectPaymentDTO=new DirectPaymentDTO();
					dDirectPaymentDTO.setQ1_OrderNo(mcamRepaymentTradeDetails.getPayOrderNumber());
					dDirectPaymentDTO.setS1_PayerName(conditionDTO.getCustName());
					dDirectPaymentDTO.setS3_PayerCardNo(idno);
					dDirectPaymentDTO.setS4_PayerBankCardNo(bindCard);
					dDirectPaymentDTO.setS7_BankMobile(conditionDTO.getMobile());
					dDirectPaymentDTO.setQ2_Amount(new BigDecimal(amount));
					dDirectPaymentDTO.setQ4_ProductName("直接代扣");
					dDirectPaymentDTO.setT2_SmsCode(conditionDTO.getT2SmsCode());
					Map<String, Object> map=hjPayApi.directPayment(dDirectPaymentDTO);//走直接代扣
					mcamRepaymentTradeDetails.setRequestNo(requestNo);
					resolveHjWithholdReturnData(mcamRepaymentTradeDetails,map);
				}else{
					conditionDTO.setOrderNo(orderNo);
					mcamRepaymentTradeDetails = hjInitWithhold(conditionDTO);
					//先查询汇聚的绑卡记录是否存在
					McfePaymentUserBindCardCondition McfePaymentUserBindCardCondition = new McfePaymentUserBindCardCondition();
					McfePaymentUserBindCardCondition.setIdno(idno);
					McfePaymentUserBindCardCondition.setBankCardNo(bindCard);
					McfePaymentUserBindCardCondition.setChannel(channel);
					McfePaymentUserBindCardCondition.setStatus("BIND_SUCCESS");
					McfePaymentUserBindCard mcamPaymentUserBindCard = mcamPaymentUserBindCardMapper.selectByCondition(McfePaymentUserBindCardCondition);
					if(mcamPaymentUserBindCard!=null && StringUtils.isNotEmpty(mcamPaymentUserBindCard.getBindOrderId())){//记录不是空且签约号不是空
						AgreementPaymentDTO agreementPaymentDTO=new AgreementPaymentDTO();
						agreementPaymentDTO.setQ1_OrderNo(orderNo);
						agreementPaymentDTO.setQ2_Amount(new BigDecimal(amount));
						agreementPaymentDTO.setQ4_ProductName("协议代扣");
						agreementPaymentDTO.setS9_bankSignId(mcamPaymentUserBindCard.getBindOrderId());
						agreementPaymentDTO.setS4_PayerBankCardNo(mcamPaymentUserBindCard.getBankCardNo());
						Map<String, Object> map=hjPayApi.agreementPayment(agreementPaymentDTO);//走协议代扣
						resolveHjWithholdReturnData(mcamRepaymentTradeDetails,map);
					}else{
						DirectPaymentDTO dDirectPaymentDTO=new DirectPaymentDTO();
						dDirectPaymentDTO.setQ1_OrderNo(orderNo);
						McfeLendingProcess mcfeLendingProcess=mcfeLendingProcessDao.selectByCustIdNumber(idno);
						dDirectPaymentDTO.setS1_PayerName(mcfeLendingProcess.getCustName());
						dDirectPaymentDTO.setS3_PayerCardNo(idno);
						dDirectPaymentDTO.setS4_PayerBankCardNo(bindCard);
						dDirectPaymentDTO.setS7_BankMobile(mcfeLendingProcess.getCustMobile());
						dDirectPaymentDTO.setQ2_Amount(new BigDecimal(amount));
						dDirectPaymentDTO.setQ4_ProductName("直接代扣");
						Map<String, Object> map=hjPayApi.directPayment(dDirectPaymentDTO);//走直接代扣
						resolveHjWithholdReturnData(mcamRepaymentTradeDetails,map);
					}
				}
			}
			if (PayContants.PAY_CHANNEL_BF.getCode().equals(channel)) {// 宝付通道
				String orderNo = GenerateReqNoUtils.transctionReq2("BFXYDK", 24);
				mcamRepaymentTradeDetails = initBfWithhold(requestNo,idno, bindCard, amount, title, channel,orderNo);
				BaoFuDirectPaymentDTO paymentDTO = new BaoFuDirectPaymentDTO();
				paymentDTO.setAmount(amount);
				paymentDTO.setBankNumber(mcamRepaymentTradeDetails.getBankNumber());
				paymentDTO.setRealName(mcamRepaymentTradeDetails.getCustName());
				paymentDTO.setIdNumber(mcamRepaymentTradeDetails.getIdNumber());
				paymentDTO.setMobile(mcamRepaymentTradeDetails.getMobileNo());
				paymentDTO.setLoanId(conditionDTO.getLoanId());
				paymentDTO.setOrderNumber(orderNo);
				paymentDTO.setProtocolNo(mcamRepaymentTradeDetails.getBindOrderId());
				Map<String, Object> map = null;// 走协议代扣
				if(conditionDTO.getPayType().equals(100)){
					map = bfPayApi.baoFuTransPayment(paymentDTO);
				}else{
					map = bfPayApi.baoFuDirectPayment(paymentDTO);
				}
				MarvelsLogUtil.getInstance().info("map:"+map.toString());
				resolveHjWithholdReturnData(mcamRepaymentTradeDetails, map);
			}
			if (PayContants.PAY_CHANNEL_KQ.getCode().equals(channel)) {// 快钱通道
//				String orderNo = GenerateReqNoUtils.transctionReq2("KQXYDK", 24);
//				mcamRepaymentTradeDetails = initBfWithhold(requestNo,idno, bindCard, amount, title, channel, orderNo);
//				KqDirectPaymentDTO kqDirectPaymentDTO = new KqDirectPaymentDTO();
//				kqDirectPaymentDTO.setAmount(amount);
//				kqDirectPaymentDTO.setExternalRefNumber(mcamRepaymentTradeDetails.getPayOrderNumber());
//				kqDirectPaymentDTO.setEntryTime(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
//				kqDirectPaymentDTO.setPayToken(mcamRepaymentTradeDetails.getBindOrderId());
//				kqDirectPaymentDTO.setCustomerId(idno);
//				kqDirectPaymentDTO.setLoanId(conditionDTO.getLoanId());
//				Map<String, Object> map = kqPayApi.kuaiQianDirectPayment(kqDirectPaymentDTO);// 走协议代扣
//				resolveHjWithholdReturnData(mcamRepaymentTradeDetails, map);
			}
			if (PayContants.PAY_CHANNEL_CJ.getCode().equals(channel)) {// 畅捷通道
				String orderNo = GenerateReqNoUtils.transctionReq2("CJXYDK", 24);
				mcamRepaymentTradeDetails = initBfWithhold(requestNo,idno, bindCard, amount, title, channel, orderNo);
				com.marvels.financial.pay.cjpay.dto.DirectPaymentDTO directPaymentDTO = new com.marvels.financial.pay.cjpay.dto.DirectPaymentDTO();
				directPaymentDTO.setTrxId(mcamRepaymentTradeDetails.getPayOrderNumber());
				directPaymentDTO.setMerUserId(idno);
				directPaymentDTO.setCardNo(mcamRepaymentTradeDetails.getBankNumber());
				directPaymentDTO.setTrxAmt(amount);
				directPaymentDTO.setLoanId(conditionDTO.getLoanId());
				Map<String, Object> map = cjPayApi.directPayment(directPaymentDTO);// 走协议代扣
				resolveHjWithholdReturnData(mcamRepaymentTradeDetails, map);
			}
			return MarvelsPayResultDTO.getSuccessResult(mcamRepaymentTradeDetails);
		} catch (MarvelsBusinessException e1){
			return MarvelsPayResultDTO.getFailResult("-1", e1.getMessage());
		}catch (Exception e) {
			logger.error("withhold============idno="+idno+",bindCard="+bindCard+",amount="+amount+"channel="+channel+"异常",e);
			if(mcamRepaymentTradeDetails!=null){
				mcamRepaymentTradeDetails.setResult("-3");
				mcamRepaymentTradeDetails.setUpdatedDate(new Date());
				mcamRepaymentTradeDetailsMapper.updateByPrimaryKeySelective(mcamRepaymentTradeDetails);
			}
			return MarvelsPayResultDTO.getFailResult("-2", "系统异常");
		}
	}




	@Override
	public Map<String, Object> directPaymentSms(RepaymentNoMobileDTO repaymentNoMobileDTO)
			throws MarvelsBusinessException {
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getS1PayerName())){
			throw new MarvelsBusinessException("姓名不能为空");
		}
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getS3PayerCardNo())){
			throw new MarvelsBusinessException("身份证不能为空");
		}
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getS4PayerBankCardNo())){
			throw new MarvelsBusinessException("银行卡号不能为空");
		}
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getS7BankMobile())){
			throw new MarvelsBusinessException("手机号不能为空");
		}
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getLoanId())){
			throw new MarvelsBusinessException("进件单号不能为空");
		}
		if(StringUtils.isEmpty(repaymentNoMobileDTO.getWithholdCategory())){
			throw new MarvelsBusinessException("扣款类别不能为空");
		}
		if("2".equals(repaymentNoMobileDTO.getWithholdCategory())){
			if(StringUtils.isEmpty(repaymentNoMobileDTO.getType())){
				throw new MarvelsBusinessException("展期类别不能为空");
			}
		}
		Map<String, Object> map=new HashMap<String, Object>();
		String paymentChannel  = ServerProperties.getValue(configPropertiesPath, "common.properties", "payment_channel");
		if(paymentChannel.equals(PayContants.PAY_CHANNEL_HJ.getCode())){//汇聚
			String orderNo=GenerateReqNoUtils.transctionReq2("HJKJDK",24);
			WithholdConditionDTO withholdConditionDTO=new WithholdConditionDTO();
			String reqNo = GenerateReqNoUtils.transctionReq("TX");
			String amount="";
			if("2".equals(repaymentNoMobileDTO.getWithholdCategory())){//扣展期
				ExtensionFunctionConditionDTO dto=new ExtensionFunctionConditionDTO();
				dto.setType(repaymentNoMobileDTO.getType());
				dto.setLoanId(repaymentNoMobileDTO.getLoanId());
				dto=extensionFunctionApi.selectExtensionInfo(dto);
				amount=String.valueOf(dto.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
			}else{
				amount = String.valueOf(iLoanAfterInfoApi.queryCurrentTenorMoney(repaymentNoMobileDTO.getLoanId()));
			}
			withholdConditionDTO.setAmount(amount);
			withholdConditionDTO.setType(repaymentNoMobileDTO.getWithholdWay());
			withholdConditionDTO.setBankName(repaymentNoMobileDTO.getBankName());
			withholdConditionDTO.setBindCard(repaymentNoMobileDTO.getS4PayerBankCardNo());
			withholdConditionDTO.setChannel(paymentChannel);
			withholdConditionDTO.setCustName(repaymentNoMobileDTO.getS1PayerName());
			withholdConditionDTO.setIdno(repaymentNoMobileDTO.getS3PayerCardNo());
			withholdConditionDTO.setRequestNo(reqNo);
			withholdConditionDTO.setMobile(repaymentNoMobileDTO.getS7BankMobile());
			withholdConditionDTO.setTitle("直接代扣");
			withholdConditionDTO.setOrderNo(orderNo);
			hjInitWithhold(withholdConditionDTO);
			DirectPaymentSmsDTO directPaymentSmsDTO=new DirectPaymentSmsDTO();
			transferDirectPay(directPaymentSmsDTO,withholdConditionDTO);
			map=hjPayApi.directPaymentSms(directPaymentSmsDTO);//走直接代扣
		}else{
			map.put("status",MarvelsConstant.FAILED);
			map.put("errormsg","暂不支持该支付通道");
		}
		return map;
	}

	/**
	 * 直接代扣-短信条件dto转换
	 * @param directPaymentSmsDTO
	 * @param withholdConditionDTO
	 */
	private void transferDirectPay(DirectPaymentSmsDTO directPaymentSmsDTO,WithholdConditionDTO withholdConditionDTO){
		directPaymentSmsDTO.setQ1_OrderNo(withholdConditionDTO.getOrderNo());
		directPaymentSmsDTO.setQ2_Amount(new BigDecimal(withholdConditionDTO.getAmount()));
		directPaymentSmsDTO.setS1_PayerName(withholdConditionDTO.getCustName());
		directPaymentSmsDTO.setS3_PayerCardNo(withholdConditionDTO.getIdno());
		directPaymentSmsDTO.setS4_PayerBankCardNo(withholdConditionDTO.getBindCard());
		directPaymentSmsDTO.setS7_BankMobile(withholdConditionDTO.getMobile());
	}

}
